babylon.max.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403
  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. /** @hidden */
  441. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  442. // Rebuild shaders source code
  443. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  444. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  445. vertexCode = prefix + vertexCode;
  446. fragmentCode = prefix + fragmentCode;
  447. // Number lines of shaders source code
  448. var i = 2;
  449. var regex = /\n/gm;
  450. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  451. i = 2;
  452. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  453. // Dump shaders name and formatted source code
  454. if (this.name.vertexElement) {
  455. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  456. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  457. }
  458. else if (this.name.vertex) {
  459. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  460. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  461. }
  462. else {
  463. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  464. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  465. }
  466. };
  467. ;
  468. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  469. var preparedSourceCode = this._processPrecision(sourceCode);
  470. if (this._engine.webGLVersion == 1) {
  471. callback(preparedSourceCode);
  472. return;
  473. }
  474. // Already converted
  475. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  476. callback(preparedSourceCode.replace("#version 300 es", ""));
  477. return;
  478. }
  479. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  480. // Remove extensions
  481. // #extension GL_OES_standard_derivatives : enable
  482. // #extension GL_EXT_shader_texture_lod : enable
  483. // #extension GL_EXT_frag_depth : enable
  484. // #extension GL_EXT_draw_buffers : require
  485. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  486. var result = preparedSourceCode.replace(regex, "");
  487. // Migrate to GLSL v300
  488. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  489. result = result.replace(/attribute[ \t]/g, "in ");
  490. result = result.replace(/[ \t]attribute/g, " in");
  491. if (isFragment) {
  492. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  494. result = result.replace(/texture2D\s*\(/g, "texture(");
  495. result = result.replace(/textureCube\s*\(/g, "texture(");
  496. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  497. result = result.replace(/gl_FragColor/g, "glFragColor");
  498. result = result.replace(/gl_FragData/g, "glFragData");
  499. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  500. }
  501. callback(result);
  502. };
  503. Effect.prototype._processIncludes = function (sourceCode, callback) {
  504. var _this = this;
  505. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  506. var match = regex.exec(sourceCode);
  507. var returnValue = new String(sourceCode);
  508. while (match != null) {
  509. var includeFile = match[1];
  510. // Uniform declaration
  511. if (includeFile.indexOf("__decl__") !== -1) {
  512. includeFile = includeFile.replace(/__decl__/, "");
  513. if (this._engine.supportsUniformBuffers) {
  514. includeFile = includeFile.replace(/Vertex/, "Ubo");
  515. includeFile = includeFile.replace(/Fragment/, "Ubo");
  516. }
  517. includeFile = includeFile + "Declaration";
  518. }
  519. if (Effect.IncludesShadersStore[includeFile]) {
  520. // Substitution
  521. var includeContent = Effect.IncludesShadersStore[includeFile];
  522. if (match[2]) {
  523. var splits = match[3].split(",");
  524. for (var index = 0; index < splits.length; index += 2) {
  525. var source = new RegExp(splits[index], "g");
  526. var dest = splits[index + 1];
  527. includeContent = includeContent.replace(source, dest);
  528. }
  529. }
  530. if (match[4]) {
  531. var indexString = match[5];
  532. if (indexString.indexOf("..") !== -1) {
  533. var indexSplits = indexString.split("..");
  534. var minIndex = parseInt(indexSplits[0]);
  535. var maxIndex = parseInt(indexSplits[1]);
  536. var sourceIncludeContent = includeContent.slice(0);
  537. includeContent = "";
  538. if (isNaN(maxIndex)) {
  539. maxIndex = this._indexParameters[indexSplits[1]];
  540. }
  541. for (var i = minIndex; i < maxIndex; i++) {
  542. if (!this._engine.supportsUniformBuffers) {
  543. // Ubo replacement
  544. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  545. return p1 + "{X}";
  546. });
  547. }
  548. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  549. }
  550. }
  551. else {
  552. if (!this._engine.supportsUniformBuffers) {
  553. // Ubo replacement
  554. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  555. return p1 + "{X}";
  556. });
  557. }
  558. includeContent = includeContent.replace(/\{X\}/g, indexString);
  559. }
  560. }
  561. // Replace
  562. returnValue = returnValue.replace(match[0], includeContent);
  563. }
  564. else {
  565. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  566. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  567. Effect.IncludesShadersStore[includeFile] = fileContent;
  568. _this._processIncludes(returnValue, callback);
  569. });
  570. return;
  571. }
  572. match = regex.exec(sourceCode);
  573. }
  574. callback(returnValue);
  575. };
  576. Effect.prototype._processPrecision = function (source) {
  577. if (source.indexOf("precision highp float") === -1) {
  578. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  579. source = "precision mediump float;\n" + source;
  580. }
  581. else {
  582. source = "precision highp float;\n" + source;
  583. }
  584. }
  585. else {
  586. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  587. source = source.replace("precision highp float", "precision mediump float");
  588. }
  589. }
  590. return source;
  591. };
  592. /**
  593. * Recompiles the webGL program
  594. * @param vertexSourceCode The source code for the vertex shader.
  595. * @param fragmentSourceCode The source code for the fragment shader.
  596. * @param onCompiled Callback called when completed.
  597. * @param onError Callback called on error.
  598. */
  599. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  600. var _this = this;
  601. this._isReady = false;
  602. this._vertexSourceCodeOverride = vertexSourceCode;
  603. this._fragmentSourceCodeOverride = fragmentSourceCode;
  604. this.onError = function (effect, error) {
  605. if (onError) {
  606. onError(error);
  607. }
  608. };
  609. this.onCompiled = function () {
  610. var scenes = _this.getEngine().scenes;
  611. for (var i = 0; i < scenes.length; i++) {
  612. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  613. }
  614. if (onCompiled) {
  615. onCompiled(_this._program);
  616. }
  617. };
  618. this._fallbacks = null;
  619. this._prepareEffect();
  620. };
  621. /**
  622. * Gets the uniform locations of the the specified variable names
  623. * @param names THe names of the variables to lookup.
  624. * @returns Array of locations in the same order as variable names.
  625. */
  626. Effect.prototype.getSpecificUniformLocations = function (names) {
  627. var engine = this._engine;
  628. return engine.getUniforms(this._program, names);
  629. };
  630. /**
  631. * Prepares the effect
  632. */
  633. Effect.prototype._prepareEffect = function () {
  634. var attributesNames = this._attributesNames;
  635. var defines = this.defines;
  636. var fallbacks = this._fallbacks;
  637. this._valueCache = {};
  638. var previousProgram = this._program;
  639. try {
  640. var engine = this._engine;
  641. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  642. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  643. }
  644. else {
  645. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  646. }
  647. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  648. if (engine.supportsUniformBuffers) {
  649. for (var name in this._uniformBuffersNames) {
  650. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  651. }
  652. }
  653. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  654. this._attributes = engine.getAttributes(this._program, attributesNames);
  655. var index;
  656. for (index = 0; index < this._samplers.length; index++) {
  657. var sampler = this.getUniform(this._samplers[index]);
  658. if (sampler == null) {
  659. this._samplers.splice(index, 1);
  660. index--;
  661. }
  662. }
  663. engine.bindSamplers(this);
  664. this._compilationError = "";
  665. this._isReady = true;
  666. if (this.onCompiled) {
  667. this.onCompiled(this);
  668. }
  669. this.onCompileObservable.notifyObservers(this);
  670. this.onCompileObservable.clear();
  671. // Unbind mesh reference in fallbacks
  672. if (this._fallbacks) {
  673. this._fallbacks.unBindMesh();
  674. }
  675. if (previousProgram) {
  676. this.getEngine()._deleteProgram(previousProgram);
  677. }
  678. }
  679. catch (e) {
  680. this._compilationError = e.message;
  681. // Let's go through fallbacks then
  682. BABYLON.Tools.Error("Unable to compile effect:");
  683. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  684. return " " + uniform;
  685. }));
  686. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  687. return " " + attribute;
  688. }));
  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. if (x === void 0) { x = 0; }
  2217. if (y === void 0) { y = 0; }
  2218. this.x = x;
  2219. this.y = y;
  2220. }
  2221. /**
  2222. * Gets a string with the Vector2 coordinates
  2223. * @returns a string with the Vector2 coordinates
  2224. */
  2225. Vector2.prototype.toString = function () {
  2226. return "{X: " + this.x + " Y:" + this.y + "}";
  2227. };
  2228. /**
  2229. * Gets class name
  2230. * @returns the string "Vector2"
  2231. */
  2232. Vector2.prototype.getClassName = function () {
  2233. return "Vector2";
  2234. };
  2235. /**
  2236. * Gets current vector hash code
  2237. * @returns the Vector2 hash code as a number
  2238. */
  2239. Vector2.prototype.getHashCode = function () {
  2240. var hash = this.x || 0;
  2241. hash = (hash * 397) ^ (this.y || 0);
  2242. return hash;
  2243. };
  2244. // Operators
  2245. /**
  2246. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2247. * @param array defines the source array
  2248. * @param index defines the offset in source array
  2249. * @returns the current Vector2
  2250. */
  2251. Vector2.prototype.toArray = function (array, index) {
  2252. if (index === void 0) { index = 0; }
  2253. array[index] = this.x;
  2254. array[index + 1] = this.y;
  2255. return this;
  2256. };
  2257. /**
  2258. * Copy the current vector to an array
  2259. * @returns a new array with 2 elements: the Vector2 coordinates.
  2260. */
  2261. Vector2.prototype.asArray = function () {
  2262. var result = new Array();
  2263. this.toArray(result, 0);
  2264. return result;
  2265. };
  2266. /**
  2267. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2268. * @param source defines the source Vector2
  2269. * @returns the current updated Vector2
  2270. */
  2271. Vector2.prototype.copyFrom = function (source) {
  2272. this.x = source.x;
  2273. this.y = source.y;
  2274. return this;
  2275. };
  2276. /**
  2277. * Sets the Vector2 coordinates with the given floats
  2278. * @param x defines the first coordinate
  2279. * @param y defines the second coordinate
  2280. * @returns the current updated Vector2
  2281. */
  2282. Vector2.prototype.copyFromFloats = function (x, y) {
  2283. this.x = x;
  2284. this.y = y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Sets the Vector2 coordinates with the given floats
  2289. * @param x defines the first coordinate
  2290. * @param y defines the second coordinate
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.set = function (x, y) {
  2294. return this.copyFromFloats(x, y);
  2295. };
  2296. /**
  2297. * Add another vector with the current one
  2298. * @param otherVector defines the other vector
  2299. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2300. */
  2301. Vector2.prototype.add = function (otherVector) {
  2302. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2303. };
  2304. /**
  2305. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2306. * @param otherVector defines the other vector
  2307. * @param result defines the target vector
  2308. * @returns the unmodified current Vector2
  2309. */
  2310. Vector2.prototype.addToRef = function (otherVector, result) {
  2311. result.x = this.x + otherVector.x;
  2312. result.y = this.y + otherVector.y;
  2313. return this;
  2314. };
  2315. /**
  2316. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2317. * @param otherVector defines the other vector
  2318. * @returns the current updated Vector2
  2319. */
  2320. Vector2.prototype.addInPlace = function (otherVector) {
  2321. this.x += otherVector.x;
  2322. this.y += otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns a new Vector2
  2329. */
  2330. Vector2.prototype.addVector3 = function (otherVector) {
  2331. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2332. };
  2333. /**
  2334. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2335. * @param otherVector defines the other vector
  2336. * @returns a new Vector2
  2337. */
  2338. Vector2.prototype.subtract = function (otherVector) {
  2339. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2340. };
  2341. /**
  2342. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2343. * @param otherVector defines the other vector
  2344. * @param result defines the target vector
  2345. * @returns the unmodified current Vector2
  2346. */
  2347. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2348. result.x = this.x - otherVector.x;
  2349. result.y = this.y - otherVector.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2354. * @param otherVector defines the other vector
  2355. * @returns the current updated Vector2
  2356. */
  2357. Vector2.prototype.subtractInPlace = function (otherVector) {
  2358. this.x -= otherVector.x;
  2359. this.y -= otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Multiplies in place the current Vector2 coordinates by the given ones
  2364. * @param otherVector defines the other vector
  2365. * @returns the current updated Vector2
  2366. */
  2367. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2368. this.x *= otherVector.x;
  2369. this.y *= otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns a new Vector2
  2376. */
  2377. Vector2.prototype.multiply = function (otherVector) {
  2378. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2379. };
  2380. /**
  2381. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2382. * @param otherVector defines the other vector
  2383. * @param result defines the target vector
  2384. * @returns the unmodified current Vector2
  2385. */
  2386. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2387. result.x = this.x * otherVector.x;
  2388. result.y = this.y * otherVector.y;
  2389. return this;
  2390. };
  2391. /**
  2392. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2393. * @param x defines the first coordinate
  2394. * @param y defines the second coordinate
  2395. * @returns a new Vector2
  2396. */
  2397. Vector2.prototype.multiplyByFloats = function (x, y) {
  2398. return new Vector2(this.x * x, this.y * y);
  2399. };
  2400. /**
  2401. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2402. * @param otherVector defines the other vector
  2403. * @returns a new Vector2
  2404. */
  2405. Vector2.prototype.divide = function (otherVector) {
  2406. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2407. };
  2408. /**
  2409. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2410. * @param otherVector defines the other vector
  2411. * @param result defines the target vector
  2412. * @returns the unmodified current Vector2
  2413. */
  2414. Vector2.prototype.divideToRef = function (otherVector, result) {
  2415. result.x = this.x / otherVector.x;
  2416. result.y = this.y / otherVector.y;
  2417. return this;
  2418. };
  2419. /**
  2420. * Divides the current Vector3 coordinates by the given ones
  2421. * @param otherVector defines the other vector
  2422. * @returns the current updated Vector2
  2423. */
  2424. Vector2.prototype.divideInPlace = function (otherVector) {
  2425. return this.divideToRef(otherVector, this);
  2426. };
  2427. /**
  2428. * Gets a new Vector2 with current Vector2 negated coordinates
  2429. * @returns a new Vector2
  2430. */
  2431. Vector2.prototype.negate = function () {
  2432. return new Vector2(-this.x, -this.y);
  2433. };
  2434. /**
  2435. * Multiply the Vector2 coordinates by scale
  2436. * @param scale defines the scaling factor
  2437. * @returns the current updated Vector2
  2438. */
  2439. Vector2.prototype.scaleInPlace = function (scale) {
  2440. this.x *= scale;
  2441. this.y *= scale;
  2442. return this;
  2443. };
  2444. /**
  2445. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2446. * @param scale defines the scaling factor
  2447. * @returns a new Vector2
  2448. */
  2449. Vector2.prototype.scale = function (scale) {
  2450. var result = new Vector2(0, 0);
  2451. this.scaleToRef(scale, result);
  2452. return result;
  2453. };
  2454. /**
  2455. * Scale the current Vector2 values by a factor to a given Vector2
  2456. * @param scale defines the scale factor
  2457. * @param result defines the Vector2 object where to store the result
  2458. * @returns the unmodified current Vector2
  2459. */
  2460. Vector2.prototype.scaleToRef = function (scale, result) {
  2461. result.x = this.x * scale;
  2462. result.y = this.y * scale;
  2463. return this;
  2464. };
  2465. /**
  2466. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2467. * @param scale defines the scale factor
  2468. * @param result defines the Vector2 object where to store the result
  2469. * @returns the unmodified current Vector2
  2470. */
  2471. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2472. result.x += this.x * scale;
  2473. result.y += this.y * scale;
  2474. return this;
  2475. };
  2476. /**
  2477. * Gets a boolean if two vectors are equals
  2478. * @param otherVector defines the other vector
  2479. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2480. */
  2481. Vector2.prototype.equals = function (otherVector) {
  2482. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2483. };
  2484. /**
  2485. * Gets a boolean if two vectors are equals (using an epsilon value)
  2486. * @param otherVector defines the other vector
  2487. * @param epsilon defines the minimal distance to consider equality
  2488. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2489. */
  2490. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2491. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2492. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2493. };
  2494. // Properties
  2495. /**
  2496. * Gets the length of the vector
  2497. * @returns the vector length (float)
  2498. */
  2499. Vector2.prototype.length = function () {
  2500. return Math.sqrt(this.x * this.x + this.y * this.y);
  2501. };
  2502. /**
  2503. * Gets the vector squared length
  2504. * @returns the vector squared length (float)
  2505. */
  2506. Vector2.prototype.lengthSquared = function () {
  2507. return (this.x * this.x + this.y * this.y);
  2508. };
  2509. // Methods
  2510. /**
  2511. * Normalize the vector
  2512. * @returns the current updated Vector2
  2513. */
  2514. Vector2.prototype.normalize = function () {
  2515. var len = this.length();
  2516. if (len === 0)
  2517. return this;
  2518. var num = 1.0 / len;
  2519. this.x *= num;
  2520. this.y *= num;
  2521. return this;
  2522. };
  2523. /**
  2524. * Gets a new Vector2 copied from the Vector2
  2525. * @returns a new Vector2
  2526. */
  2527. Vector2.prototype.clone = function () {
  2528. return new Vector2(this.x, this.y);
  2529. };
  2530. // Statics
  2531. /**
  2532. * Gets a new Vector2(0, 0)
  2533. * @returns a new Vector2
  2534. */
  2535. Vector2.Zero = function () {
  2536. return new Vector2(0, 0);
  2537. };
  2538. /**
  2539. * Gets a new Vector2(1, 1)
  2540. * @returns a new Vector2
  2541. */
  2542. Vector2.One = function () {
  2543. return new Vector2(1, 1);
  2544. };
  2545. /**
  2546. * Gets a new Vector2 set from the given index element of the given array
  2547. * @param array defines the data source
  2548. * @param offset defines the offset in the data source
  2549. * @returns a new Vector2
  2550. */
  2551. Vector2.FromArray = function (array, offset) {
  2552. if (offset === void 0) { offset = 0; }
  2553. return new Vector2(array[offset], array[offset + 1]);
  2554. };
  2555. /**
  2556. * Sets "result" from the given index element of the given array
  2557. * @param array defines the data source
  2558. * @param offset defines the offset in the data source
  2559. * @param result defines the target vector
  2560. */
  2561. Vector2.FromArrayToRef = function (array, offset, result) {
  2562. result.x = array[offset];
  2563. result.y = array[offset + 1];
  2564. };
  2565. /**
  2566. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2567. * @param value1 defines 1st point of control
  2568. * @param value2 defines 2nd point of control
  2569. * @param value3 defines 3rd point of control
  2570. * @param value4 defines 4th point of control
  2571. * @param amount defines the interpolation factor
  2572. * @returns a new Vector2
  2573. */
  2574. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2575. var squared = amount * amount;
  2576. var cubed = amount * squared;
  2577. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2578. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2579. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2580. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2581. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2582. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2583. return new Vector2(x, y);
  2584. };
  2585. /**
  2586. * 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".
  2587. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2588. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2589. * @param value defines the value to clamp
  2590. * @param min defines the lower limit
  2591. * @param max defines the upper limit
  2592. * @returns a new Vector2
  2593. */
  2594. Vector2.Clamp = function (value, min, max) {
  2595. var x = value.x;
  2596. x = (x > max.x) ? max.x : x;
  2597. x = (x < min.x) ? min.x : x;
  2598. var y = value.y;
  2599. y = (y > max.y) ? max.y : y;
  2600. y = (y < min.y) ? min.y : y;
  2601. return new Vector2(x, y);
  2602. };
  2603. /**
  2604. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2605. * @param value1 defines the 1st control point
  2606. * @param tangent1 defines the outgoing tangent
  2607. * @param value2 defines the 2nd control point
  2608. * @param tangent2 defines the incoming tangent
  2609. * @param amount defines the interpolation factor
  2610. * @returns a new Vector2
  2611. */
  2612. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2613. var squared = amount * amount;
  2614. var cubed = amount * squared;
  2615. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2616. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2617. var part3 = (cubed - (2.0 * squared)) + amount;
  2618. var part4 = cubed - squared;
  2619. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2620. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2621. return new Vector2(x, y);
  2622. };
  2623. /**
  2624. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2625. * @param start defines the start vector
  2626. * @param end defines the end vector
  2627. * @param amount defines the interpolation factor
  2628. * @returns a new Vector2
  2629. */
  2630. Vector2.Lerp = function (start, end, amount) {
  2631. var x = start.x + ((end.x - start.x) * amount);
  2632. var y = start.y + ((end.y - start.y) * amount);
  2633. return new Vector2(x, y);
  2634. };
  2635. /**
  2636. * Gets the dot product of the vector "left" and the vector "right"
  2637. * @param left defines first vector
  2638. * @param right defines second vector
  2639. * @returns the dot product (float)
  2640. */
  2641. Vector2.Dot = function (left, right) {
  2642. return left.x * right.x + left.y * right.y;
  2643. };
  2644. /**
  2645. * Returns a new Vector2 equal to the normalized given vector
  2646. * @param vector defines the vector to normalize
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Normalize = function (vector) {
  2650. var newVector = vector.clone();
  2651. newVector.normalize();
  2652. return newVector;
  2653. };
  2654. /**
  2655. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2656. * @param left defines 1st vector
  2657. * @param right defines 2nd vector
  2658. * @returns a new Vector2
  2659. */
  2660. Vector2.Minimize = function (left, right) {
  2661. var x = (left.x < right.x) ? left.x : right.x;
  2662. var y = (left.y < right.y) ? left.y : right.y;
  2663. return new Vector2(x, y);
  2664. };
  2665. /**
  2666. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2667. * @param left defines 1st vector
  2668. * @param right defines 2nd vector
  2669. * @returns a new Vector2
  2670. */
  2671. Vector2.Maximize = function (left, right) {
  2672. var x = (left.x > right.x) ? left.x : right.x;
  2673. var y = (left.y > right.y) ? left.y : right.y;
  2674. return new Vector2(x, y);
  2675. };
  2676. /**
  2677. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2678. * @param vector defines the vector to transform
  2679. * @param transformation defines the matrix to apply
  2680. * @returns a new Vector2
  2681. */
  2682. Vector2.Transform = function (vector, transformation) {
  2683. var r = Vector2.Zero();
  2684. Vector2.TransformToRef(vector, transformation, r);
  2685. return r;
  2686. };
  2687. /**
  2688. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2689. * @param vector defines the vector to transform
  2690. * @param transformation defines the matrix to apply
  2691. * @param result defines the target vector
  2692. */
  2693. Vector2.TransformToRef = function (vector, transformation, result) {
  2694. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2695. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2696. result.x = x;
  2697. result.y = y;
  2698. };
  2699. /**
  2700. * Determines if a given vector is included in a triangle
  2701. * @param p defines the vector to test
  2702. * @param p0 defines 1st triangle point
  2703. * @param p1 defines 2nd triangle point
  2704. * @param p2 defines 3rd triangle point
  2705. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2706. */
  2707. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2708. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2709. var sign = a < 0 ? -1 : 1;
  2710. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2711. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2712. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2713. };
  2714. /**
  2715. * Gets the distance between the vectors "value1" and "value2"
  2716. * @param value1 defines first vector
  2717. * @param value2 defines second vector
  2718. * @returns the distance between vectors
  2719. */
  2720. Vector2.Distance = function (value1, value2) {
  2721. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2722. };
  2723. /**
  2724. * Returns the squared distance between the vectors "value1" and "value2"
  2725. * @param value1 defines first vector
  2726. * @param value2 defines second vector
  2727. * @returns the squared distance between vectors
  2728. */
  2729. Vector2.DistanceSquared = function (value1, value2) {
  2730. var x = value1.x - value2.x;
  2731. var y = value1.y - value2.y;
  2732. return (x * x) + (y * y);
  2733. };
  2734. /**
  2735. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2736. * @param value1 defines first vector
  2737. * @param value2 defines second vector
  2738. * @returns a new Vector2
  2739. */
  2740. Vector2.Center = function (value1, value2) {
  2741. var center = value1.add(value2);
  2742. center.scaleInPlace(0.5);
  2743. return center;
  2744. };
  2745. /**
  2746. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2747. * @param p defines the middle point
  2748. * @param segA defines one point of the segment
  2749. * @param segB defines the other point of the segment
  2750. * @returns the shortest distance
  2751. */
  2752. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2753. var l2 = Vector2.DistanceSquared(segA, segB);
  2754. if (l2 === 0.0) {
  2755. return Vector2.Distance(p, segA);
  2756. }
  2757. var v = segB.subtract(segA);
  2758. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2759. var proj = segA.add(v.multiplyByFloats(t, t));
  2760. return Vector2.Distance(p, proj);
  2761. };
  2762. return Vector2;
  2763. }());
  2764. BABYLON.Vector2 = Vector2;
  2765. /**
  2766. * Classed used to store (x,y,z) vector representation
  2767. * A Vector3 is the main object used in 3D geometry
  2768. * It can represent etiher the coordinates of a point the space, either a direction
  2769. * Reminder: Babylon.js uses a left handed forward facing system
  2770. */
  2771. var Vector3 = /** @class */ (function () {
  2772. /**
  2773. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2774. * @param x defines the first coordinates (on X axis)
  2775. * @param y defines the second coordinates (on Y axis)
  2776. * @param z defines the third coordinates (on Z axis)
  2777. */
  2778. function Vector3(
  2779. /**
  2780. * Defines the first coordinates (on X axis)
  2781. */
  2782. x,
  2783. /**
  2784. * Defines the second coordinates (on Y axis)
  2785. */
  2786. y,
  2787. /**
  2788. * Defines the third coordinates (on Z axis)
  2789. */
  2790. z) {
  2791. if (x === void 0) { x = 0; }
  2792. if (y === void 0) { y = 0; }
  2793. if (z === void 0) { z = 0; }
  2794. this.x = x;
  2795. this.y = y;
  2796. this.z = z;
  2797. }
  2798. /**
  2799. * Creates a string representation of the Vector3
  2800. * @returns a string with the Vector3 coordinates.
  2801. */
  2802. Vector3.prototype.toString = function () {
  2803. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2804. };
  2805. /**
  2806. * Gets the class name
  2807. * @returns the string "Vector3"
  2808. */
  2809. Vector3.prototype.getClassName = function () {
  2810. return "Vector3";
  2811. };
  2812. /**
  2813. * Creates the Vector3 hash code
  2814. * @returns a number which tends to be unique between Vector3 instances
  2815. */
  2816. Vector3.prototype.getHashCode = function () {
  2817. var hash = this.x || 0;
  2818. hash = (hash * 397) ^ (this.y || 0);
  2819. hash = (hash * 397) ^ (this.z || 0);
  2820. return hash;
  2821. };
  2822. // Operators
  2823. /**
  2824. * Creates an array containing three elements : the coordinates of the Vector3
  2825. * @returns a new array of numbers
  2826. */
  2827. Vector3.prototype.asArray = function () {
  2828. var result = [];
  2829. this.toArray(result, 0);
  2830. return result;
  2831. };
  2832. /**
  2833. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2834. * @param array defines the destination array
  2835. * @param index defines the offset in the destination array
  2836. * @returns the current Vector3
  2837. */
  2838. Vector3.prototype.toArray = function (array, index) {
  2839. if (index === void 0) { index = 0; }
  2840. array[index] = this.x;
  2841. array[index + 1] = this.y;
  2842. array[index + 2] = this.z;
  2843. return this;
  2844. };
  2845. /**
  2846. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2847. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2848. */
  2849. Vector3.prototype.toQuaternion = function () {
  2850. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2851. };
  2852. /**
  2853. * Adds the given vector to the current Vector3
  2854. * @param otherVector defines the second operand
  2855. * @returns the current updated Vector3
  2856. */
  2857. Vector3.prototype.addInPlace = function (otherVector) {
  2858. this.x += otherVector.x;
  2859. this.y += otherVector.y;
  2860. this.z += otherVector.z;
  2861. return this;
  2862. };
  2863. /**
  2864. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2865. * @param otherVector defines the second operand
  2866. * @returns the resulting Vector3
  2867. */
  2868. Vector3.prototype.add = function (otherVector) {
  2869. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2870. };
  2871. /**
  2872. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2873. * @param otherVector defines the second operand
  2874. * @param result defines the Vector3 object where to store the result
  2875. * @returns the current Vector3
  2876. */
  2877. Vector3.prototype.addToRef = function (otherVector, result) {
  2878. result.x = this.x + otherVector.x;
  2879. result.y = this.y + otherVector.y;
  2880. result.z = this.z + otherVector.z;
  2881. return this;
  2882. };
  2883. /**
  2884. * Subtract the given vector from the current Vector3
  2885. * @param otherVector defines the second operand
  2886. * @returns the current updated Vector3
  2887. */
  2888. Vector3.prototype.subtractInPlace = function (otherVector) {
  2889. this.x -= otherVector.x;
  2890. this.y -= otherVector.y;
  2891. this.z -= otherVector.z;
  2892. return this;
  2893. };
  2894. /**
  2895. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2896. * @param otherVector defines the second operand
  2897. * @returns the resulting Vector3
  2898. */
  2899. Vector3.prototype.subtract = function (otherVector) {
  2900. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2901. };
  2902. /**
  2903. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2904. * @param otherVector defines the second operand
  2905. * @param result defines the Vector3 object where to store the result
  2906. * @returns the current Vector3
  2907. */
  2908. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2909. result.x = this.x - otherVector.x;
  2910. result.y = this.y - otherVector.y;
  2911. result.z = this.z - otherVector.z;
  2912. return this;
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2916. * @param x defines the x coordinate of the operand
  2917. * @param y defines the y coordinate of the operand
  2918. * @param z defines the z coordinate of the operand
  2919. * @returns the resulting Vector3
  2920. */
  2921. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2922. return new Vector3(this.x - x, this.y - y, this.z - z);
  2923. };
  2924. /**
  2925. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2926. * @param x defines the x coordinate of the operand
  2927. * @param y defines the y coordinate of the operand
  2928. * @param z defines the z coordinate of the operand
  2929. * @param result defines the Vector3 object where to store the result
  2930. * @returns the current Vector3
  2931. */
  2932. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2933. result.x = this.x - x;
  2934. result.y = this.y - y;
  2935. result.z = this.z - z;
  2936. return this;
  2937. };
  2938. /**
  2939. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2940. * @returns a new Vector3
  2941. */
  2942. Vector3.prototype.negate = function () {
  2943. return new Vector3(-this.x, -this.y, -this.z);
  2944. };
  2945. /**
  2946. * Multiplies the Vector3 coordinates by the float "scale"
  2947. * @param scale defines the multiplier factor
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.scaleInPlace = function (scale) {
  2951. this.x *= scale;
  2952. this.y *= scale;
  2953. this.z *= scale;
  2954. return this;
  2955. };
  2956. /**
  2957. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2958. * @param scale defines the multiplier factor
  2959. * @returns a new Vector3
  2960. */
  2961. Vector3.prototype.scale = function (scale) {
  2962. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2963. };
  2964. /**
  2965. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2966. * @param scale defines the multiplier factor
  2967. * @param result defines the Vector3 object where to store the result
  2968. * @returns the current Vector3
  2969. */
  2970. Vector3.prototype.scaleToRef = function (scale, result) {
  2971. result.x = this.x * scale;
  2972. result.y = this.y * scale;
  2973. result.z = this.z * scale;
  2974. return this;
  2975. };
  2976. /**
  2977. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2978. * @param scale defines the scale factor
  2979. * @param result defines the Vector3 object where to store the result
  2980. * @returns the unmodified current Vector3
  2981. */
  2982. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2983. result.x += this.x * scale;
  2984. result.y += this.y * scale;
  2985. result.z += this.z * scale;
  2986. return this;
  2987. };
  2988. /**
  2989. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2990. * @param otherVector defines the second operand
  2991. * @returns true if both vectors are equals
  2992. */
  2993. Vector3.prototype.equals = function (otherVector) {
  2994. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2995. };
  2996. /**
  2997. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2998. * @param otherVector defines the second operand
  2999. * @param epsilon defines the minimal distance to define values as equals
  3000. * @returns true if both vectors are distant less than epsilon
  3001. */
  3002. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3003. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3004. 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);
  3005. };
  3006. /**
  3007. * Returns true if the current Vector3 coordinates equals the given floats
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @returns true if both vectors are equals
  3012. */
  3013. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3014. return this.x === x && this.y === y && this.z === z;
  3015. };
  3016. /**
  3017. * Multiplies the current Vector3 coordinates by the given ones
  3018. * @param otherVector defines the second operand
  3019. * @returns the current updated Vector3
  3020. */
  3021. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3022. this.x *= otherVector.x;
  3023. this.y *= otherVector.y;
  3024. this.z *= otherVector.z;
  3025. return this;
  3026. };
  3027. /**
  3028. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3029. * @param otherVector defines the second operand
  3030. * @returns the new Vector3
  3031. */
  3032. Vector3.prototype.multiply = function (otherVector) {
  3033. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3034. };
  3035. /**
  3036. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3037. * @param otherVector defines the second operand
  3038. * @param result defines the Vector3 object where to store the result
  3039. * @returns the current Vector3
  3040. */
  3041. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3042. result.x = this.x * otherVector.x;
  3043. result.y = this.y * otherVector.y;
  3044. result.z = this.z * otherVector.z;
  3045. return this;
  3046. };
  3047. /**
  3048. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3049. * @param x defines the x coordinate of the operand
  3050. * @param y defines the y coordinate of the operand
  3051. * @param z defines the z coordinate of the operand
  3052. * @returns the new Vector3
  3053. */
  3054. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3055. return new Vector3(this.x * x, this.y * y, this.z * z);
  3056. };
  3057. /**
  3058. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3059. * @param otherVector defines the second operand
  3060. * @returns the new Vector3
  3061. */
  3062. Vector3.prototype.divide = function (otherVector) {
  3063. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3064. };
  3065. /**
  3066. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3067. * @param otherVector defines the second operand
  3068. * @param result defines the Vector3 object where to store the result
  3069. * @returns the current Vector3
  3070. */
  3071. Vector3.prototype.divideToRef = function (otherVector, result) {
  3072. result.x = this.x / otherVector.x;
  3073. result.y = this.y / otherVector.y;
  3074. result.z = this.z / otherVector.z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Divides the current Vector3 coordinates by the given ones.
  3079. * @param otherVector defines the second operand
  3080. * @returns the current updated Vector3
  3081. */
  3082. Vector3.prototype.divideInPlace = function (otherVector) {
  3083. return this.divideToRef(otherVector, this);
  3084. };
  3085. /**
  3086. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3087. * @param other defines the second operand
  3088. * @returns the current updated Vector3
  3089. */
  3090. Vector3.prototype.minimizeInPlace = function (other) {
  3091. if (other.x < this.x)
  3092. this.x = other.x;
  3093. if (other.y < this.y)
  3094. this.y = other.y;
  3095. if (other.z < this.z)
  3096. this.z = other.z;
  3097. return this;
  3098. };
  3099. /**
  3100. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3101. * @param other defines the second operand
  3102. * @returns the current updated Vector3
  3103. */
  3104. Vector3.prototype.maximizeInPlace = function (other) {
  3105. if (other.x > this.x)
  3106. this.x = other.x;
  3107. if (other.y > this.y)
  3108. this.y = other.y;
  3109. if (other.z > this.z)
  3110. this.z = other.z;
  3111. return this;
  3112. };
  3113. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3114. /**
  3115. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3116. */
  3117. get: function () {
  3118. var absX = Math.abs(this.x);
  3119. var absY = Math.abs(this.y);
  3120. if (absX !== absY) {
  3121. return true;
  3122. }
  3123. var absZ = Math.abs(this.z);
  3124. if (absX !== absZ) {
  3125. return true;
  3126. }
  3127. if (absY !== absZ) {
  3128. return true;
  3129. }
  3130. return false;
  3131. },
  3132. enumerable: true,
  3133. configurable: true
  3134. });
  3135. // Properties
  3136. /**
  3137. * Gets the length of the Vector3
  3138. * @returns the length of the Vecto3
  3139. */
  3140. Vector3.prototype.length = function () {
  3141. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3142. };
  3143. /**
  3144. * Gets the squared length of the Vector3
  3145. * @returns squared length of the Vector3
  3146. */
  3147. Vector3.prototype.lengthSquared = function () {
  3148. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3149. };
  3150. /**
  3151. * Normalize the current Vector3.
  3152. * Please note that this is an in place operation.
  3153. * @returns the current updated Vector3
  3154. */
  3155. Vector3.prototype.normalize = function () {
  3156. var len = this.length();
  3157. if (len === 0 || len === 1.0)
  3158. return this;
  3159. var num = 1.0 / len;
  3160. this.x *= num;
  3161. this.y *= num;
  3162. this.z *= num;
  3163. return this;
  3164. };
  3165. /**
  3166. * Normalize the current Vector3 to a new vector
  3167. * @returns the new Vector3
  3168. */
  3169. Vector3.prototype.normalizeToNew = function () {
  3170. var normalized = new Vector3(0, 0, 0);
  3171. this.normalizeToRef(normalized);
  3172. return normalized;
  3173. };
  3174. /**
  3175. * Normalize the current Vector3 to the reference
  3176. * @param reference define the Vector3 to update
  3177. * @returns the updated Vector3
  3178. */
  3179. Vector3.prototype.normalizeToRef = function (reference) {
  3180. var len = this.length();
  3181. if (len === 0 || len === 1.0) {
  3182. reference.set(this.x, this.y, this.z);
  3183. return reference;
  3184. }
  3185. var scale = 1.0 / len;
  3186. this.scaleToRef(scale, reference);
  3187. return reference;
  3188. };
  3189. /**
  3190. * Creates a new Vector3 copied from the current Vector3
  3191. * @returns the new Vector3
  3192. */
  3193. Vector3.prototype.clone = function () {
  3194. return new Vector3(this.x, this.y, this.z);
  3195. };
  3196. /**
  3197. * Copies the given vector coordinates to the current Vector3 ones
  3198. * @param source defines the source Vector3
  3199. * @returns the current updated Vector3
  3200. */
  3201. Vector3.prototype.copyFrom = function (source) {
  3202. this.x = source.x;
  3203. this.y = source.y;
  3204. this.z = source.z;
  3205. return this;
  3206. };
  3207. /**
  3208. * Copies the given floats to the current Vector3 coordinates
  3209. * @param x defines the x coordinate of the operand
  3210. * @param y defines the y coordinate of the operand
  3211. * @param z defines the z coordinate of the operand
  3212. * @returns the current updated Vector3
  3213. */
  3214. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3215. this.x = x;
  3216. this.y = y;
  3217. this.z = z;
  3218. return this;
  3219. };
  3220. /**
  3221. * Copies the given floats to the current Vector3 coordinates
  3222. * @param x defines the x coordinate of the operand
  3223. * @param y defines the y coordinate of the operand
  3224. * @param z defines the z coordinate of the operand
  3225. * @returns the current updated Vector3
  3226. */
  3227. Vector3.prototype.set = function (x, y, z) {
  3228. return this.copyFromFloats(x, y, z);
  3229. };
  3230. // Statics
  3231. /**
  3232. * Get the clip factor between two vectors
  3233. * @param vector0 defines the first operand
  3234. * @param vector1 defines the second operand
  3235. * @param axis defines the axis to use
  3236. * @param size defines the size along the axis
  3237. * @returns the clip factor
  3238. */
  3239. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3240. var d0 = Vector3.Dot(vector0, axis) - size;
  3241. var d1 = Vector3.Dot(vector1, axis) - size;
  3242. var s = d0 / (d0 - d1);
  3243. return s;
  3244. };
  3245. /**
  3246. * Get angle between two vectors
  3247. * @param vector0 angle between vector0 and vector1
  3248. * @param vector1 angle between vector0 and vector1
  3249. * @param normal direction of the normal
  3250. * @return the angle between vector0 and vector1
  3251. */
  3252. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3253. var v0 = vector0.clone().normalize();
  3254. var v1 = vector1.clone().normalize();
  3255. var dot = Vector3.Dot(v0, v1);
  3256. var n = Vector3.Cross(v0, v1);
  3257. if (Vector3.Dot(n, normal) > 0) {
  3258. return Math.acos(dot);
  3259. }
  3260. return -Math.acos(dot);
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set from the index "offset" of the given array
  3264. * @param array defines the source array
  3265. * @param offset defines the offset in the source array
  3266. * @returns the new Vector3
  3267. */
  3268. Vector3.FromArray = function (array, offset) {
  3269. if (!offset) {
  3270. offset = 0;
  3271. }
  3272. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3273. };
  3274. /**
  3275. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3276. * This function is deprecated. Use FromArray instead
  3277. * @param array defines the source array
  3278. * @param offset defines the offset in the source array
  3279. * @returns the new Vector3
  3280. */
  3281. Vector3.FromFloatArray = function (array, offset) {
  3282. return Vector3.FromArray(array, offset);
  3283. };
  3284. /**
  3285. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3286. * @param array defines the source array
  3287. * @param offset defines the offset in the source array
  3288. * @param result defines the Vector3 where to store the result
  3289. */
  3290. Vector3.FromArrayToRef = function (array, offset, result) {
  3291. result.x = array[offset];
  3292. result.y = array[offset + 1];
  3293. result.z = array[offset + 2];
  3294. };
  3295. /**
  3296. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3297. * This function is deprecated. Use FromArrayToRef instead.
  3298. * @param array defines the source array
  3299. * @param offset defines the offset in the source array
  3300. * @param result defines the Vector3 where to store the result
  3301. */
  3302. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3303. return Vector3.FromArrayToRef(array, offset, result);
  3304. };
  3305. /**
  3306. * Sets the given vector "result" with the given floats.
  3307. * @param x defines the x coordinate of the source
  3308. * @param y defines the y coordinate of the source
  3309. * @param z defines the z coordinate of the source
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3313. result.x = x;
  3314. result.y = y;
  3315. result.z = z;
  3316. };
  3317. /**
  3318. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3319. * @returns a new empty Vector3
  3320. */
  3321. Vector3.Zero = function () {
  3322. return new Vector3(0.0, 0.0, 0.0);
  3323. };
  3324. /**
  3325. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3326. * @returns a new unit Vector3
  3327. */
  3328. Vector3.One = function () {
  3329. return new Vector3(1.0, 1.0, 1.0);
  3330. };
  3331. /**
  3332. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3333. * @returns a new up Vector3
  3334. */
  3335. Vector3.Up = function () {
  3336. return new Vector3(0.0, 1.0, 0.0);
  3337. };
  3338. /**
  3339. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3340. * @returns a new down Vector3
  3341. */
  3342. Vector3.Down = function () {
  3343. return new Vector3(0.0, -1.0, 0.0);
  3344. };
  3345. /**
  3346. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3347. * @returns a new forward Vector3
  3348. */
  3349. Vector3.Forward = function () {
  3350. return new Vector3(0.0, 0.0, 1.0);
  3351. };
  3352. /**
  3353. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3354. * @returns a new right Vector3
  3355. */
  3356. Vector3.Right = function () {
  3357. return new Vector3(1.0, 0.0, 0.0);
  3358. };
  3359. /**
  3360. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3361. * @returns a new left Vector3
  3362. */
  3363. Vector3.Left = function () {
  3364. return new Vector3(-1.0, 0.0, 0.0);
  3365. };
  3366. /**
  3367. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3368. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @returns the transformed Vector3
  3372. */
  3373. Vector3.TransformCoordinates = function (vector, transformation) {
  3374. var result = Vector3.Zero();
  3375. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3376. return result;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3380. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3381. * @param vector defines the Vector3 to transform
  3382. * @param transformation defines the transformation matrix
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3386. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3387. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3388. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3389. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3390. result.x = x / w;
  3391. result.y = y / w;
  3392. result.z = z / w;
  3393. };
  3394. /**
  3395. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3396. * This method computes tranformed coordinates only, not transformed direction vectors
  3397. * @param x define the x coordinate of the source vector
  3398. * @param y define the y coordinate of the source vector
  3399. * @param z define the z coordinate of the source vector
  3400. * @param transformation defines the transformation matrix
  3401. * @param result defines the Vector3 where to store the result
  3402. */
  3403. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3404. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3405. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3406. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3407. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3408. result.x = rx / rw;
  3409. result.y = ry / rw;
  3410. result.z = rz / rw;
  3411. };
  3412. /**
  3413. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param vector defines the Vector3 to transform
  3416. * @param transformation defines the transformation matrix
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.TransformNormal = function (vector, transformation) {
  3420. var result = Vector3.Zero();
  3421. Vector3.TransformNormalToRef(vector, transformation, result);
  3422. return result;
  3423. };
  3424. /**
  3425. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3426. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3427. * @param vector defines the Vector3 to transform
  3428. * @param transformation defines the transformation matrix
  3429. * @param result defines the Vector3 where to store the result
  3430. */
  3431. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3432. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3433. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3434. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3435. result.x = x;
  3436. result.y = y;
  3437. result.z = z;
  3438. };
  3439. /**
  3440. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3441. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3442. * @param x define the x coordinate of the source vector
  3443. * @param y define the y coordinate of the source vector
  3444. * @param z define the z coordinate of the source vector
  3445. * @param transformation defines the transformation matrix
  3446. * @param result defines the Vector3 where to store the result
  3447. */
  3448. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3449. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3450. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3451. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3452. };
  3453. /**
  3454. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3455. * @param value1 defines the first control point
  3456. * @param value2 defines the second control point
  3457. * @param value3 defines the third control point
  3458. * @param value4 defines the fourth control point
  3459. * @param amount defines the amount on the spline to use
  3460. * @returns the new Vector3
  3461. */
  3462. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3463. var squared = amount * amount;
  3464. var cubed = amount * squared;
  3465. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3466. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3467. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3468. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3469. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3470. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3471. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3472. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3473. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3474. return new Vector3(x, y, z);
  3475. };
  3476. /**
  3477. * 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"
  3478. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3479. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3480. * @param value defines the current value
  3481. * @param min defines the lower range value
  3482. * @param max defines the upper range value
  3483. * @returns the new Vector3
  3484. */
  3485. Vector3.Clamp = function (value, min, max) {
  3486. var x = value.x;
  3487. x = (x > max.x) ? max.x : x;
  3488. x = (x < min.x) ? min.x : x;
  3489. var y = value.y;
  3490. y = (y > max.y) ? max.y : y;
  3491. y = (y < min.y) ? min.y : y;
  3492. var z = value.z;
  3493. z = (z > max.z) ? max.z : z;
  3494. z = (z < min.z) ? min.z : z;
  3495. return new Vector3(x, y, z);
  3496. };
  3497. /**
  3498. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3499. * @param value1 defines the first control point
  3500. * @param tangent1 defines the first tangent vector
  3501. * @param value2 defines the second control point
  3502. * @param tangent2 defines the second tangent vector
  3503. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3504. * @returns the new Vector3
  3505. */
  3506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3507. var squared = amount * amount;
  3508. var cubed = amount * squared;
  3509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3511. var part3 = (cubed - (2.0 * squared)) + amount;
  3512. var part4 = cubed - squared;
  3513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3516. return new Vector3(x, y, z);
  3517. };
  3518. /**
  3519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3520. * @param start defines the start value
  3521. * @param end defines the end value
  3522. * @param amount max defines amount between both (between 0 and 1)
  3523. * @returns the new Vector3
  3524. */
  3525. Vector3.Lerp = function (start, end, amount) {
  3526. var result = new Vector3(0, 0, 0);
  3527. Vector3.LerpToRef(start, end, amount, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3532. * @param start defines the start value
  3533. * @param end defines the end value
  3534. * @param amount max defines amount between both (between 0 and 1)
  3535. * @param result defines the Vector3 where to store the result
  3536. */
  3537. Vector3.LerpToRef = function (start, end, amount, result) {
  3538. result.x = start.x + ((end.x - start.x) * amount);
  3539. result.y = start.y + ((end.y - start.y) * amount);
  3540. result.z = start.z + ((end.z - start.z) * amount);
  3541. };
  3542. /**
  3543. * Returns the dot product (float) between the vectors "left" and "right"
  3544. * @param left defines the left operand
  3545. * @param right defines the right operand
  3546. * @returns the dot product
  3547. */
  3548. Vector3.Dot = function (left, right) {
  3549. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3550. };
  3551. /**
  3552. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3553. * The cross product is then orthogonal to both "left" and "right"
  3554. * @param left defines the left operand
  3555. * @param right defines the right operand
  3556. * @returns the cross product
  3557. */
  3558. Vector3.Cross = function (left, right) {
  3559. var result = Vector3.Zero();
  3560. Vector3.CrossToRef(left, right, result);
  3561. return result;
  3562. };
  3563. /**
  3564. * Sets the given vector "result" with the cross product of "left" and "right"
  3565. * The cross product is then orthogonal to both "left" and "right"
  3566. * @param left defines the left operand
  3567. * @param right defines the right operand
  3568. * @param result defines the Vector3 where to store the result
  3569. */
  3570. Vector3.CrossToRef = function (left, right, result) {
  3571. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3572. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3573. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3574. result.copyFrom(MathTmp.Vector3[0]);
  3575. };
  3576. /**
  3577. * Returns a new Vector3 as the normalization of the given vector
  3578. * @param vector defines the Vector3 to normalize
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.Normalize = function (vector) {
  3582. var result = Vector3.Zero();
  3583. Vector3.NormalizeToRef(vector, result);
  3584. return result;
  3585. };
  3586. /**
  3587. * Sets the given vector "result" with the normalization of the given first vector
  3588. * @param vector defines the Vector3 to normalize
  3589. * @param result defines the Vector3 where to store the result
  3590. */
  3591. Vector3.NormalizeToRef = function (vector, result) {
  3592. result.copyFrom(vector);
  3593. result.normalize();
  3594. };
  3595. /**
  3596. * Project a Vector3 onto screen space
  3597. * @param vector defines the Vector3 to project
  3598. * @param world defines the world matrix to use
  3599. * @param transform defines the transform (view x projection) matrix to use
  3600. * @param viewport defines the screen viewport to use
  3601. * @returns the new Vector3
  3602. */
  3603. Vector3.Project = function (vector, world, transform, viewport) {
  3604. var cw = viewport.width;
  3605. var ch = viewport.height;
  3606. var cx = viewport.x;
  3607. var cy = viewport.y;
  3608. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3609. 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);
  3610. var matrix = MathTmp.Matrix[0];
  3611. world.multiplyToRef(transform, matrix);
  3612. matrix.multiplyToRef(viewportMatrix, matrix);
  3613. return Vector3.TransformCoordinates(vector, matrix);
  3614. };
  3615. /**
  3616. * Unproject from screen space to object space
  3617. * @param source defines the screen space Vector3 to use
  3618. * @param viewportWidth defines the current width of the viewport
  3619. * @param viewportHeight defines the current height of the viewport
  3620. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3621. * @param transform defines the transform (view x projection) matrix to use
  3622. * @returns the new Vector3
  3623. */
  3624. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3625. var matrix = MathTmp.Matrix[0];
  3626. world.multiplyToRef(transform, matrix);
  3627. matrix.invert();
  3628. source.x = source.x / viewportWidth * 2 - 1;
  3629. source.y = -(source.y / viewportHeight * 2 - 1);
  3630. var vector = Vector3.TransformCoordinates(source, matrix);
  3631. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3632. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3633. vector = vector.scale(1.0 / num);
  3634. }
  3635. return vector;
  3636. };
  3637. /**
  3638. * Unproject from screen space to object space
  3639. * @param source defines the screen space Vector3 to use
  3640. * @param viewportWidth defines the current width of the viewport
  3641. * @param viewportHeight defines the current height of the viewport
  3642. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3643. * @param view defines the view matrix to use
  3644. * @param projection defines the projection matrix to use
  3645. * @returns the new Vector3
  3646. */
  3647. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3648. var result = Vector3.Zero();
  3649. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3650. return result;
  3651. };
  3652. /**
  3653. * Unproject from screen space to object space
  3654. * @param source defines the screen space Vector3 to use
  3655. * @param viewportWidth defines the current width of the viewport
  3656. * @param viewportHeight defines the current height of the viewport
  3657. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3658. * @param view defines the view matrix to use
  3659. * @param projection defines the projection matrix to use
  3660. * @param result defines the Vector3 where to store the result
  3661. */
  3662. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3663. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3664. };
  3665. /**
  3666. * Unproject from screen space to object space
  3667. * @param sourceX defines the screen space x coordinate to use
  3668. * @param sourceY defines the screen space y coordinate to use
  3669. * @param sourceZ defines the screen space z coordinate to use
  3670. * @param viewportWidth defines the current width of the viewport
  3671. * @param viewportHeight defines the current height of the viewport
  3672. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3673. * @param view defines the view matrix to use
  3674. * @param projection defines the projection matrix to use
  3675. * @param result defines the Vector3 where to store the result
  3676. */
  3677. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3678. var matrix = MathTmp.Matrix[0];
  3679. world.multiplyToRef(view, matrix);
  3680. matrix.multiplyToRef(projection, matrix);
  3681. matrix.invert();
  3682. var screenSource = MathTmp.Vector3[0];
  3683. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3684. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3685. screenSource.z = 2 * sourceZ - 1.0;
  3686. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3687. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3688. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3689. result.scaleInPlace(1.0 / num);
  3690. }
  3691. };
  3692. /**
  3693. * Gets the minimal coordinate values between two Vector3
  3694. * @param left defines the first operand
  3695. * @param right defines the second operand
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Minimize = function (left, right) {
  3699. var min = left.clone();
  3700. min.minimizeInPlace(right);
  3701. return min;
  3702. };
  3703. /**
  3704. * Gets the maximal coordinate values between two Vector3
  3705. * @param left defines the first operand
  3706. * @param right defines the second operand
  3707. * @returns the new Vector3
  3708. */
  3709. Vector3.Maximize = function (left, right) {
  3710. var max = left.clone();
  3711. max.maximizeInPlace(right);
  3712. return max;
  3713. };
  3714. /**
  3715. * Returns the distance between the vectors "value1" and "value2"
  3716. * @param value1 defines the first operand
  3717. * @param value2 defines the second operand
  3718. * @returns the distance
  3719. */
  3720. Vector3.Distance = function (value1, value2) {
  3721. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3722. };
  3723. /**
  3724. * Returns the squared distance between the vectors "value1" and "value2"
  3725. * @param value1 defines the first operand
  3726. * @param value2 defines the second operand
  3727. * @returns the squared distance
  3728. */
  3729. Vector3.DistanceSquared = function (value1, value2) {
  3730. var x = value1.x - value2.x;
  3731. var y = value1.y - value2.y;
  3732. var z = value1.z - value2.z;
  3733. return (x * x) + (y * y) + (z * z);
  3734. };
  3735. /**
  3736. * Returns a new Vector3 located at the center between "value1" and "value2"
  3737. * @param value1 defines the first operand
  3738. * @param value2 defines the second operand
  3739. * @returns the new Vector3
  3740. */
  3741. Vector3.Center = function (value1, value2) {
  3742. var center = value1.add(value2);
  3743. center.scaleInPlace(0.5);
  3744. return center;
  3745. };
  3746. /**
  3747. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3748. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3749. * to something in order to rotate it from its local system to the given target system
  3750. * Note: axis1, axis2 and axis3 are normalized during this operation
  3751. * @param axis1 defines the first axis
  3752. * @param axis2 defines the second axis
  3753. * @param axis3 defines the third axis
  3754. * @returns a new Vector3
  3755. */
  3756. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3757. var rotation = Vector3.Zero();
  3758. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3759. return rotation;
  3760. };
  3761. /**
  3762. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3763. * @param axis1 defines the first axis
  3764. * @param axis2 defines the second axis
  3765. * @param axis3 defines the third axis
  3766. * @param ref defines the Vector3 where to store the result
  3767. */
  3768. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3769. var quat = MathTmp.Quaternion[0];
  3770. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3771. quat.toEulerAnglesToRef(ref);
  3772. };
  3773. return Vector3;
  3774. }());
  3775. BABYLON.Vector3 = Vector3;
  3776. //Vector4 class created for EulerAngle class conversion to Quaternion
  3777. var Vector4 = /** @class */ (function () {
  3778. /**
  3779. * Creates a Vector4 object from the given floats.
  3780. */
  3781. function Vector4(x, y, z, w) {
  3782. this.x = x;
  3783. this.y = y;
  3784. this.z = z;
  3785. this.w = w;
  3786. }
  3787. /**
  3788. * Returns the string with the Vector4 coordinates.
  3789. */
  3790. Vector4.prototype.toString = function () {
  3791. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3792. };
  3793. /**
  3794. * Returns the string "Vector4".
  3795. */
  3796. Vector4.prototype.getClassName = function () {
  3797. return "Vector4";
  3798. };
  3799. /**
  3800. * Returns the Vector4 hash code.
  3801. */
  3802. Vector4.prototype.getHashCode = function () {
  3803. var hash = this.x || 0;
  3804. hash = (hash * 397) ^ (this.y || 0);
  3805. hash = (hash * 397) ^ (this.z || 0);
  3806. hash = (hash * 397) ^ (this.w || 0);
  3807. return hash;
  3808. };
  3809. // Operators
  3810. /**
  3811. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3812. */
  3813. Vector4.prototype.asArray = function () {
  3814. var result = new Array();
  3815. this.toArray(result, 0);
  3816. return result;
  3817. };
  3818. /**
  3819. * Populates the given array from the given index with the Vector4 coordinates.
  3820. * Returns the Vector4.
  3821. */
  3822. Vector4.prototype.toArray = function (array, index) {
  3823. if (index === undefined) {
  3824. index = 0;
  3825. }
  3826. array[index] = this.x;
  3827. array[index + 1] = this.y;
  3828. array[index + 2] = this.z;
  3829. array[index + 3] = this.w;
  3830. return this;
  3831. };
  3832. /**
  3833. * Adds the given vector to the current Vector4.
  3834. * Returns the updated Vector4.
  3835. */
  3836. Vector4.prototype.addInPlace = function (otherVector) {
  3837. this.x += otherVector.x;
  3838. this.y += otherVector.y;
  3839. this.z += otherVector.z;
  3840. this.w += otherVector.w;
  3841. return this;
  3842. };
  3843. /**
  3844. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3845. */
  3846. Vector4.prototype.add = function (otherVector) {
  3847. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3848. };
  3849. /**
  3850. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3851. * Returns the current Vector4.
  3852. */
  3853. Vector4.prototype.addToRef = function (otherVector, result) {
  3854. result.x = this.x + otherVector.x;
  3855. result.y = this.y + otherVector.y;
  3856. result.z = this.z + otherVector.z;
  3857. result.w = this.w + otherVector.w;
  3858. return this;
  3859. };
  3860. /**
  3861. * Subtract in place the given vector from the current Vector4.
  3862. * Returns the updated Vector4.
  3863. */
  3864. Vector4.prototype.subtractInPlace = function (otherVector) {
  3865. this.x -= otherVector.x;
  3866. this.y -= otherVector.y;
  3867. this.z -= otherVector.z;
  3868. this.w -= otherVector.w;
  3869. return this;
  3870. };
  3871. /**
  3872. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3873. */
  3874. Vector4.prototype.subtract = function (otherVector) {
  3875. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3876. };
  3877. /**
  3878. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3879. * Returns the current Vector4.
  3880. */
  3881. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3882. result.x = this.x - otherVector.x;
  3883. result.y = this.y - otherVector.y;
  3884. result.z = this.z - otherVector.z;
  3885. result.w = this.w - otherVector.w;
  3886. return this;
  3887. };
  3888. /**
  3889. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3890. */
  3891. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3892. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3893. };
  3894. /**
  3895. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3896. * Returns the current Vector4.
  3897. */
  3898. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3899. result.x = this.x - x;
  3900. result.y = this.y - y;
  3901. result.z = this.z - z;
  3902. result.w = this.w - w;
  3903. return this;
  3904. };
  3905. /**
  3906. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3907. */
  3908. Vector4.prototype.negate = function () {
  3909. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3910. };
  3911. /**
  3912. * Multiplies the current Vector4 coordinates by scale (float).
  3913. * Returns the updated Vector4.
  3914. */
  3915. Vector4.prototype.scaleInPlace = function (scale) {
  3916. this.x *= scale;
  3917. this.y *= scale;
  3918. this.z *= scale;
  3919. this.w *= scale;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3924. */
  3925. Vector4.prototype.scale = function (scale) {
  3926. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3927. };
  3928. /**
  3929. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3930. * Returns the current Vector4.
  3931. */
  3932. Vector4.prototype.scaleToRef = function (scale, result) {
  3933. result.x = this.x * scale;
  3934. result.y = this.y * scale;
  3935. result.z = this.z * scale;
  3936. result.w = this.w * scale;
  3937. return this;
  3938. };
  3939. /**
  3940. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3941. * @param scale defines the scale factor
  3942. * @param result defines the Vector4 object where to store the result
  3943. * @returns the unmodified current Vector4
  3944. */
  3945. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3946. result.x += this.x * scale;
  3947. result.y += this.y * scale;
  3948. result.z += this.z * scale;
  3949. result.w += this.w * scale;
  3950. return this;
  3951. };
  3952. /**
  3953. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3954. */
  3955. Vector4.prototype.equals = function (otherVector) {
  3956. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3957. };
  3958. /**
  3959. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3960. */
  3961. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3962. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3963. return otherVector
  3964. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3965. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3966. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3967. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3968. };
  3969. /**
  3970. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3971. */
  3972. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3973. return this.x === x && this.y === y && this.z === z && this.w === w;
  3974. };
  3975. /**
  3976. * Multiplies in place the current Vector4 by the given one.
  3977. * Returns the updated Vector4.
  3978. */
  3979. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3980. this.x *= otherVector.x;
  3981. this.y *= otherVector.y;
  3982. this.z *= otherVector.z;
  3983. this.w *= otherVector.w;
  3984. return this;
  3985. };
  3986. /**
  3987. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3988. */
  3989. Vector4.prototype.multiply = function (otherVector) {
  3990. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3991. };
  3992. /**
  3993. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3994. * Returns the current Vector4.
  3995. */
  3996. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3997. result.x = this.x * otherVector.x;
  3998. result.y = this.y * otherVector.y;
  3999. result.z = this.z * otherVector.z;
  4000. result.w = this.w * otherVector.w;
  4001. return this;
  4002. };
  4003. /**
  4004. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4005. */
  4006. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4007. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4008. };
  4009. /**
  4010. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4011. */
  4012. Vector4.prototype.divide = function (otherVector) {
  4013. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4014. };
  4015. /**
  4016. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4017. * Returns the current Vector4.
  4018. */
  4019. Vector4.prototype.divideToRef = function (otherVector, result) {
  4020. result.x = this.x / otherVector.x;
  4021. result.y = this.y / otherVector.y;
  4022. result.z = this.z / otherVector.z;
  4023. result.w = this.w / otherVector.w;
  4024. return this;
  4025. };
  4026. /**
  4027. * Divides the current Vector3 coordinates by the given ones.
  4028. * @returns the updated Vector3.
  4029. */
  4030. Vector4.prototype.divideInPlace = function (otherVector) {
  4031. return this.divideToRef(otherVector, this);
  4032. };
  4033. /**
  4034. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4035. * @param other defines the second operand
  4036. * @returns the current updated Vector4
  4037. */
  4038. Vector4.prototype.minimizeInPlace = function (other) {
  4039. if (other.x < this.x)
  4040. this.x = other.x;
  4041. if (other.y < this.y)
  4042. this.y = other.y;
  4043. if (other.z < this.z)
  4044. this.z = other.z;
  4045. if (other.w < this.w)
  4046. this.w = other.w;
  4047. return this;
  4048. };
  4049. /**
  4050. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4051. * @param other defines the second operand
  4052. * @returns the current updated Vector4
  4053. */
  4054. Vector4.prototype.maximizeInPlace = function (other) {
  4055. if (other.x > this.x)
  4056. this.x = other.x;
  4057. if (other.y > this.y)
  4058. this.y = other.y;
  4059. if (other.z > this.z)
  4060. this.z = other.z;
  4061. if (other.w > this.w)
  4062. this.w = other.w;
  4063. return this;
  4064. };
  4065. // Properties
  4066. /**
  4067. * Returns the Vector4 length (float).
  4068. */
  4069. Vector4.prototype.length = function () {
  4070. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4071. };
  4072. /**
  4073. * Returns the Vector4 squared length (float).
  4074. */
  4075. Vector4.prototype.lengthSquared = function () {
  4076. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4077. };
  4078. // Methods
  4079. /**
  4080. * Normalizes in place the Vector4.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.normalize = function () {
  4084. var len = this.length();
  4085. if (len === 0)
  4086. return this;
  4087. var num = 1.0 / len;
  4088. this.x *= num;
  4089. this.y *= num;
  4090. this.z *= num;
  4091. this.w *= num;
  4092. return this;
  4093. };
  4094. /**
  4095. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4096. */
  4097. Vector4.prototype.toVector3 = function () {
  4098. return new Vector3(this.x, this.y, this.z);
  4099. };
  4100. /**
  4101. * Returns a new Vector4 copied from the current one.
  4102. */
  4103. Vector4.prototype.clone = function () {
  4104. return new Vector4(this.x, this.y, this.z, this.w);
  4105. };
  4106. /**
  4107. * Updates the current Vector4 with the given one coordinates.
  4108. * Returns the updated Vector4.
  4109. */
  4110. Vector4.prototype.copyFrom = function (source) {
  4111. this.x = source.x;
  4112. this.y = source.y;
  4113. this.z = source.z;
  4114. this.w = source.w;
  4115. return this;
  4116. };
  4117. /**
  4118. * Updates the current Vector4 coordinates with the given floats.
  4119. * Returns the updated Vector4.
  4120. */
  4121. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4122. this.x = x;
  4123. this.y = y;
  4124. this.z = z;
  4125. this.w = w;
  4126. return this;
  4127. };
  4128. /**
  4129. * Updates the current Vector4 coordinates with the given floats.
  4130. * Returns the updated Vector4.
  4131. */
  4132. Vector4.prototype.set = function (x, y, z, w) {
  4133. return this.copyFromFloats(x, y, z, w);
  4134. };
  4135. // Statics
  4136. /**
  4137. * Returns a new Vector4 set from the starting index of the given array.
  4138. */
  4139. Vector4.FromArray = function (array, offset) {
  4140. if (!offset) {
  4141. offset = 0;
  4142. }
  4143. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4144. };
  4145. /**
  4146. * Updates the given vector "result" from the starting index of the given array.
  4147. */
  4148. Vector4.FromArrayToRef = function (array, offset, result) {
  4149. result.x = array[offset];
  4150. result.y = array[offset + 1];
  4151. result.z = array[offset + 2];
  4152. result.w = array[offset + 3];
  4153. };
  4154. /**
  4155. * Updates the given vector "result" from the starting index of the given Float32Array.
  4156. */
  4157. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4158. Vector4.FromArrayToRef(array, offset, result);
  4159. };
  4160. /**
  4161. * Updates the given vector "result" coordinates from the given floats.
  4162. */
  4163. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4164. result.x = x;
  4165. result.y = y;
  4166. result.z = z;
  4167. result.w = w;
  4168. };
  4169. /**
  4170. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4171. */
  4172. Vector4.Zero = function () {
  4173. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4174. };
  4175. /**
  4176. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4177. */
  4178. Vector4.One = function () {
  4179. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4180. };
  4181. /**
  4182. * Returns a new normalized Vector4 from the given one.
  4183. */
  4184. Vector4.Normalize = function (vector) {
  4185. var result = Vector4.Zero();
  4186. Vector4.NormalizeToRef(vector, result);
  4187. return result;
  4188. };
  4189. /**
  4190. * Updates the given vector "result" from the normalization of the given one.
  4191. */
  4192. Vector4.NormalizeToRef = function (vector, result) {
  4193. result.copyFrom(vector);
  4194. result.normalize();
  4195. };
  4196. Vector4.Minimize = function (left, right) {
  4197. var min = left.clone();
  4198. min.minimizeInPlace(right);
  4199. return min;
  4200. };
  4201. Vector4.Maximize = function (left, right) {
  4202. var max = left.clone();
  4203. max.maximizeInPlace(right);
  4204. return max;
  4205. };
  4206. /**
  4207. * Returns the distance (float) between the vectors "value1" and "value2".
  4208. */
  4209. Vector4.Distance = function (value1, value2) {
  4210. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4211. };
  4212. /**
  4213. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4214. */
  4215. Vector4.DistanceSquared = function (value1, value2) {
  4216. var x = value1.x - value2.x;
  4217. var y = value1.y - value2.y;
  4218. var z = value1.z - value2.z;
  4219. var w = value1.w - value2.w;
  4220. return (x * x) + (y * y) + (z * z) + (w * w);
  4221. };
  4222. /**
  4223. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4224. */
  4225. Vector4.Center = function (value1, value2) {
  4226. var center = value1.add(value2);
  4227. center.scaleInPlace(0.5);
  4228. return center;
  4229. };
  4230. /**
  4231. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4232. * This methods computes transformed normalized direction vectors only.
  4233. */
  4234. Vector4.TransformNormal = function (vector, transformation) {
  4235. var result = Vector4.Zero();
  4236. Vector4.TransformNormalToRef(vector, transformation, result);
  4237. return result;
  4238. };
  4239. /**
  4240. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4241. * This methods computes transformed normalized direction vectors only.
  4242. */
  4243. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4244. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4245. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4246. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4247. result.x = x;
  4248. result.y = y;
  4249. result.z = z;
  4250. result.w = vector.w;
  4251. };
  4252. /**
  4253. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4254. * This methods computes transformed normalized direction vectors only.
  4255. */
  4256. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4257. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4258. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4259. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4260. result.w = w;
  4261. };
  4262. return Vector4;
  4263. }());
  4264. BABYLON.Vector4 = Vector4;
  4265. var Size = /** @class */ (function () {
  4266. /**
  4267. * Creates a Size object from the given width and height (floats).
  4268. */
  4269. function Size(width, height) {
  4270. this.width = width;
  4271. this.height = height;
  4272. }
  4273. // Returns a string with the Size width and height.
  4274. Size.prototype.toString = function () {
  4275. return "{W: " + this.width + ", H: " + this.height + "}";
  4276. };
  4277. /**
  4278. * Returns the string "Size"
  4279. */
  4280. Size.prototype.getClassName = function () {
  4281. return "Size";
  4282. };
  4283. /**
  4284. * Returns the Size hash code.
  4285. */
  4286. Size.prototype.getHashCode = function () {
  4287. var hash = this.width || 0;
  4288. hash = (hash * 397) ^ (this.height || 0);
  4289. return hash;
  4290. };
  4291. /**
  4292. * Updates the current size from the given one.
  4293. * Returns the updated Size.
  4294. */
  4295. Size.prototype.copyFrom = function (src) {
  4296. this.width = src.width;
  4297. this.height = src.height;
  4298. };
  4299. /**
  4300. * Updates in place the current Size from the given floats.
  4301. * Returns the updated Size.
  4302. */
  4303. Size.prototype.copyFromFloats = function (width, height) {
  4304. this.width = width;
  4305. this.height = height;
  4306. return this;
  4307. };
  4308. /**
  4309. * Updates in place the current Size from the given floats.
  4310. * Returns the updated Size.
  4311. */
  4312. Size.prototype.set = function (width, height) {
  4313. return this.copyFromFloats(width, height);
  4314. };
  4315. /**
  4316. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4317. */
  4318. Size.prototype.multiplyByFloats = function (w, h) {
  4319. return new Size(this.width * w, this.height * h);
  4320. };
  4321. /**
  4322. * Returns a new Size copied from the given one.
  4323. */
  4324. Size.prototype.clone = function () {
  4325. return new Size(this.width, this.height);
  4326. };
  4327. /**
  4328. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4329. */
  4330. Size.prototype.equals = function (other) {
  4331. if (!other) {
  4332. return false;
  4333. }
  4334. return (this.width === other.width) && (this.height === other.height);
  4335. };
  4336. Object.defineProperty(Size.prototype, "surface", {
  4337. /**
  4338. * Returns the surface of the Size : width * height (float).
  4339. */
  4340. get: function () {
  4341. return this.width * this.height;
  4342. },
  4343. enumerable: true,
  4344. configurable: true
  4345. });
  4346. /**
  4347. * Returns a new Size set to (0.0, 0.0)
  4348. */
  4349. Size.Zero = function () {
  4350. return new Size(0.0, 0.0);
  4351. };
  4352. /**
  4353. * Returns a new Size set as the addition result of the current Size and the given one.
  4354. */
  4355. Size.prototype.add = function (otherSize) {
  4356. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4357. return r;
  4358. };
  4359. /**
  4360. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4361. */
  4362. Size.prototype.subtract = function (otherSize) {
  4363. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4364. return r;
  4365. };
  4366. /**
  4367. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4368. */
  4369. Size.Lerp = function (start, end, amount) {
  4370. var w = start.width + ((end.width - start.width) * amount);
  4371. var h = start.height + ((end.height - start.height) * amount);
  4372. return new Size(w, h);
  4373. };
  4374. return Size;
  4375. }());
  4376. BABYLON.Size = Size;
  4377. /**
  4378. * Class used to store quaternion data
  4379. * @see https://en.wikipedia.org/wiki/Quaternion
  4380. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4381. */
  4382. var Quaternion = /** @class */ (function () {
  4383. /**
  4384. * Creates a new Quaternion from the given floats
  4385. * @param x defines the first component (0 by default)
  4386. * @param y defines the second component (0 by default)
  4387. * @param z defines the third component (0 by default)
  4388. * @param w defines the fourth component (1.0 by default)
  4389. */
  4390. function Quaternion(
  4391. /** defines the first component (0 by default) */
  4392. x,
  4393. /** defines the second component (0 by default) */
  4394. y,
  4395. /** defines the third component (0 by default) */
  4396. z,
  4397. /** defines the fourth component (1.0 by default) */
  4398. w) {
  4399. if (x === void 0) { x = 0.0; }
  4400. if (y === void 0) { y = 0.0; }
  4401. if (z === void 0) { z = 0.0; }
  4402. if (w === void 0) { w = 1.0; }
  4403. this.x = x;
  4404. this.y = y;
  4405. this.z = z;
  4406. this.w = w;
  4407. }
  4408. /**
  4409. * Gets a string representation for the current quaternion
  4410. * @returns a string with the Quaternion coordinates
  4411. */
  4412. Quaternion.prototype.toString = function () {
  4413. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4414. };
  4415. /**
  4416. * Gets the class name of the quaternion
  4417. * @returns the string "Quaternion"
  4418. */
  4419. Quaternion.prototype.getClassName = function () {
  4420. return "Quaternion";
  4421. };
  4422. /**
  4423. * Gets a hash code for this quaternion
  4424. * @returns the quaternion hash code
  4425. */
  4426. Quaternion.prototype.getHashCode = function () {
  4427. var hash = this.x || 0;
  4428. hash = (hash * 397) ^ (this.y || 0);
  4429. hash = (hash * 397) ^ (this.z || 0);
  4430. hash = (hash * 397) ^ (this.w || 0);
  4431. return hash;
  4432. };
  4433. /**
  4434. * Copy the quaternion to an array
  4435. * @returns a new array populated with 4 elements from the quaternion coordinates
  4436. */
  4437. Quaternion.prototype.asArray = function () {
  4438. return [this.x, this.y, this.z, this.w];
  4439. };
  4440. /**
  4441. * Check if two quaternions are equals
  4442. * @param otherQuaternion defines the second operand
  4443. * @return true if the current quaternion and the given one coordinates are strictly equals
  4444. */
  4445. Quaternion.prototype.equals = function (otherQuaternion) {
  4446. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4447. };
  4448. /**
  4449. * Clone the current quaternion
  4450. * @returns a new quaternion copied from the current one
  4451. */
  4452. Quaternion.prototype.clone = function () {
  4453. return new Quaternion(this.x, this.y, this.z, this.w);
  4454. };
  4455. /**
  4456. * Copy a quaternion to the current one
  4457. * @param other defines the other quaternion
  4458. * @returns the updated current quaternion
  4459. */
  4460. Quaternion.prototype.copyFrom = function (other) {
  4461. this.x = other.x;
  4462. this.y = other.y;
  4463. this.z = other.z;
  4464. this.w = other.w;
  4465. return this;
  4466. };
  4467. /**
  4468. * Updates the current quaternion with the given float coordinates
  4469. * @param x defines the x coordinate
  4470. * @param y defines the y coordinate
  4471. * @param z defines the z coordinate
  4472. * @param w defines the w coordinate
  4473. * @returns the updated current quaternion
  4474. */
  4475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4476. this.x = x;
  4477. this.y = y;
  4478. this.z = z;
  4479. this.w = w;
  4480. return this;
  4481. };
  4482. /**
  4483. * Updates the current quaternion from the given float coordinates
  4484. * @param x defines the x coordinate
  4485. * @param y defines the y coordinate
  4486. * @param z defines the z coordinate
  4487. * @param w defines the w coordinate
  4488. * @returns the updated current quaternion
  4489. */
  4490. Quaternion.prototype.set = function (x, y, z, w) {
  4491. return this.copyFromFloats(x, y, z, w);
  4492. };
  4493. /**
  4494. * Adds two quaternions
  4495. * @param other defines the second operand
  4496. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4497. */
  4498. Quaternion.prototype.add = function (other) {
  4499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4500. };
  4501. /**
  4502. * Add a quaternion to the current one
  4503. * @param other defines the quaternion to add
  4504. * @returns the current quaternion
  4505. */
  4506. Quaternion.prototype.addInPlace = function (other) {
  4507. this.x += other.x;
  4508. this.y += other.y;
  4509. this.z += other.z;
  4510. this.w += other.w;
  4511. return this;
  4512. };
  4513. /**
  4514. * Subtract two quaternions
  4515. * @param other defines the second operand
  4516. * @returns a new quaternion as the subtraction result of the given one from the current one
  4517. */
  4518. Quaternion.prototype.subtract = function (other) {
  4519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4520. };
  4521. /**
  4522. * Multiplies the current quaternion by a scale factor
  4523. * @param value defines the scale factor
  4524. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4525. */
  4526. Quaternion.prototype.scale = function (value) {
  4527. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4528. };
  4529. /**
  4530. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4531. * @param scale defines the scale factor
  4532. * @param result defines the Quaternion object where to store the result
  4533. * @returns the unmodified current quaternion
  4534. */
  4535. Quaternion.prototype.scaleToRef = function (scale, result) {
  4536. result.x = this.x * scale;
  4537. result.y = this.y * scale;
  4538. result.z = this.z * scale;
  4539. result.w = this.w * scale;
  4540. return this;
  4541. };
  4542. /**
  4543. * Multiplies in place the current quaternion by a scale factor
  4544. * @param value defines the scale factor
  4545. * @returns the current modified quaternion
  4546. */
  4547. Quaternion.prototype.scaleInPlace = function (value) {
  4548. this.x *= value;
  4549. this.y *= value;
  4550. this.z *= value;
  4551. this.w *= value;
  4552. return this;
  4553. };
  4554. /**
  4555. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4556. * @param scale defines the scale factor
  4557. * @param result defines the Quaternion object where to store the result
  4558. * @returns the unmodified current quaternion
  4559. */
  4560. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4561. result.x += this.x * scale;
  4562. result.y += this.y * scale;
  4563. result.z += this.z * scale;
  4564. result.w += this.w * scale;
  4565. return this;
  4566. };
  4567. /**
  4568. * Multiplies two quaternions
  4569. * @param q1 defines the second operand
  4570. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4571. */
  4572. Quaternion.prototype.multiply = function (q1) {
  4573. var result = new Quaternion(0, 0, 0, 1.0);
  4574. this.multiplyToRef(q1, result);
  4575. return result;
  4576. };
  4577. /**
  4578. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4579. * @param q1 defines the second operand
  4580. * @param result defines the target quaternion
  4581. * @returns the current quaternion
  4582. */
  4583. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4584. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4585. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4586. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4587. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4588. result.copyFromFloats(x, y, z, w);
  4589. return this;
  4590. };
  4591. /**
  4592. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4593. * @param q1 defines the second operand
  4594. * @returns the currentupdated quaternion
  4595. */
  4596. Quaternion.prototype.multiplyInPlace = function (q1) {
  4597. this.multiplyToRef(q1, this);
  4598. return this;
  4599. };
  4600. /**
  4601. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4602. * @param ref defines the target quaternion
  4603. * @returns the current quaternion
  4604. */
  4605. Quaternion.prototype.conjugateToRef = function (ref) {
  4606. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4607. return this;
  4608. };
  4609. /**
  4610. * Conjugates in place (1-q) the current quaternion
  4611. * @returns the current updated quaternion
  4612. */
  4613. Quaternion.prototype.conjugateInPlace = function () {
  4614. this.x *= -1;
  4615. this.y *= -1;
  4616. this.z *= -1;
  4617. return this;
  4618. };
  4619. /**
  4620. * Conjugates in place (1-q) the current quaternion
  4621. * @returns a new quaternion
  4622. */
  4623. Quaternion.prototype.conjugate = function () {
  4624. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4625. return result;
  4626. };
  4627. /**
  4628. * Gets length of current quaternion
  4629. * @returns the quaternion length (float)
  4630. */
  4631. Quaternion.prototype.length = function () {
  4632. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4633. };
  4634. /**
  4635. * Normalize in place the current quaternion
  4636. * @returns the current updated quaternion
  4637. */
  4638. Quaternion.prototype.normalize = function () {
  4639. var length = 1.0 / this.length();
  4640. this.x *= length;
  4641. this.y *= length;
  4642. this.z *= length;
  4643. this.w *= length;
  4644. return this;
  4645. };
  4646. /**
  4647. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4648. * @param order is a reserved parameter and is ignore for now
  4649. * @returns a new Vector3 containing the Euler angles
  4650. */
  4651. Quaternion.prototype.toEulerAngles = function (order) {
  4652. if (order === void 0) { order = "YZX"; }
  4653. var result = Vector3.Zero();
  4654. this.toEulerAnglesToRef(result, order);
  4655. return result;
  4656. };
  4657. /**
  4658. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4659. * @param result defines the vector which will be filled with the Euler angles
  4660. * @param order is a reserved parameter and is ignore for now
  4661. * @returns the current unchanged quaternion
  4662. */
  4663. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4664. if (order === void 0) { order = "YZX"; }
  4665. var qz = this.z;
  4666. var qx = this.x;
  4667. var qy = this.y;
  4668. var qw = this.w;
  4669. var sqw = qw * qw;
  4670. var sqz = qz * qz;
  4671. var sqx = qx * qx;
  4672. var sqy = qy * qy;
  4673. var zAxisY = qy * qz - qx * qw;
  4674. var limit = .4999999;
  4675. if (zAxisY < -limit) {
  4676. result.y = 2 * Math.atan2(qy, qw);
  4677. result.x = Math.PI / 2;
  4678. result.z = 0;
  4679. }
  4680. else if (zAxisY > limit) {
  4681. result.y = 2 * Math.atan2(qy, qw);
  4682. result.x = -Math.PI / 2;
  4683. result.z = 0;
  4684. }
  4685. else {
  4686. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4687. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4688. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4689. }
  4690. return this;
  4691. };
  4692. /**
  4693. * Updates the given rotation matrix with the current quaternion values
  4694. * @param result defines the target matrix
  4695. * @returns the current unchanged quaternion
  4696. */
  4697. Quaternion.prototype.toRotationMatrix = function (result) {
  4698. var xx = this.x * this.x;
  4699. var yy = this.y * this.y;
  4700. var zz = this.z * this.z;
  4701. var xy = this.x * this.y;
  4702. var zw = this.z * this.w;
  4703. var zx = this.z * this.x;
  4704. var yw = this.y * this.w;
  4705. var yz = this.y * this.z;
  4706. var xw = this.x * this.w;
  4707. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4708. result.m[1] = 2.0 * (xy + zw);
  4709. result.m[2] = 2.0 * (zx - yw);
  4710. result.m[3] = 0;
  4711. result.m[4] = 2.0 * (xy - zw);
  4712. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4713. result.m[6] = 2.0 * (yz + xw);
  4714. result.m[7] = 0;
  4715. result.m[8] = 2.0 * (zx + yw);
  4716. result.m[9] = 2.0 * (yz - xw);
  4717. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4718. result.m[11] = 0;
  4719. result.m[12] = 0;
  4720. result.m[13] = 0;
  4721. result.m[14] = 0;
  4722. result.m[15] = 1.0;
  4723. result._markAsUpdated();
  4724. return this;
  4725. };
  4726. /**
  4727. * Updates the current quaternion from the given rotation matrix values
  4728. * @param matrix defines the source matrix
  4729. * @returns the current updated quaternion
  4730. */
  4731. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4732. Quaternion.FromRotationMatrixToRef(matrix, this);
  4733. return this;
  4734. };
  4735. // Statics
  4736. /**
  4737. * Creates a new quaternion from a rotation matrix
  4738. * @param matrix defines the source matrix
  4739. * @returns a new quaternion created from the given rotation matrix values
  4740. */
  4741. Quaternion.FromRotationMatrix = function (matrix) {
  4742. var result = new Quaternion();
  4743. Quaternion.FromRotationMatrixToRef(matrix, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Updates the given quaternion with the given rotation matrix values
  4748. * @param matrix defines the source matrix
  4749. * @param result defines the target quaternion
  4750. */
  4751. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4752. var data = matrix.m;
  4753. var m11 = data[0], m12 = data[4], m13 = data[8];
  4754. var m21 = data[1], m22 = data[5], m23 = data[9];
  4755. var m31 = data[2], m32 = data[6], m33 = data[10];
  4756. var trace = m11 + m22 + m33;
  4757. var s;
  4758. if (trace > 0) {
  4759. s = 0.5 / Math.sqrt(trace + 1.0);
  4760. result.w = 0.25 / s;
  4761. result.x = (m32 - m23) * s;
  4762. result.y = (m13 - m31) * s;
  4763. result.z = (m21 - m12) * s;
  4764. }
  4765. else if (m11 > m22 && m11 > m33) {
  4766. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4767. result.w = (m32 - m23) / s;
  4768. result.x = 0.25 * s;
  4769. result.y = (m12 + m21) / s;
  4770. result.z = (m13 + m31) / s;
  4771. }
  4772. else if (m22 > m33) {
  4773. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4774. result.w = (m13 - m31) / s;
  4775. result.x = (m12 + m21) / s;
  4776. result.y = 0.25 * s;
  4777. result.z = (m23 + m32) / s;
  4778. }
  4779. else {
  4780. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4781. result.w = (m21 - m12) / s;
  4782. result.x = (m13 + m31) / s;
  4783. result.y = (m23 + m32) / s;
  4784. result.z = 0.25 * s;
  4785. }
  4786. };
  4787. /**
  4788. * Returns the dot product (float) between the quaternions "left" and "right"
  4789. * @param left defines the left operand
  4790. * @param right defines the right operand
  4791. * @returns the dot product
  4792. */
  4793. Quaternion.Dot = function (left, right) {
  4794. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4795. };
  4796. /**
  4797. * Checks if the two quaternions are close to each other
  4798. * @param quat0 defines the first quaternion to check
  4799. * @param quat1 defines the second quaternion to check
  4800. * @returns true if the two quaternions are close to each other
  4801. */
  4802. Quaternion.AreClose = function (quat0, quat1) {
  4803. var dot = Quaternion.Dot(quat0, quat1);
  4804. return dot >= 0;
  4805. };
  4806. /**
  4807. * Creates an empty quaternion
  4808. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4809. */
  4810. Quaternion.Zero = function () {
  4811. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4812. };
  4813. /**
  4814. * Inverse a given quaternion
  4815. * @param q defines the source quaternion
  4816. * @returns a new quaternion as the inverted current quaternion
  4817. */
  4818. Quaternion.Inverse = function (q) {
  4819. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4820. };
  4821. /**
  4822. * Creates an identity quaternion
  4823. * @returns the identity quaternion
  4824. */
  4825. Quaternion.Identity = function () {
  4826. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4827. };
  4828. /**
  4829. * Gets a boolean indicating if the given quaternion is identity
  4830. * @param quaternion defines the quaternion to check
  4831. * @returns true if the quaternion is identity
  4832. */
  4833. Quaternion.IsIdentity = function (quaternion) {
  4834. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4835. };
  4836. /**
  4837. * Creates a quaternion from a rotation around an axis
  4838. * @param axis defines the axis to use
  4839. * @param angle defines the angle to use
  4840. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4841. */
  4842. Quaternion.RotationAxis = function (axis, angle) {
  4843. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4844. };
  4845. /**
  4846. * Creates a rotation around an axis and stores it into the given quaternion
  4847. * @param axis defines the axis to use
  4848. * @param angle defines the angle to use
  4849. * @param result defines the target quaternion
  4850. * @returns the target quaternion
  4851. */
  4852. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4853. var sin = Math.sin(angle / 2);
  4854. axis.normalize();
  4855. result.w = Math.cos(angle / 2);
  4856. result.x = axis.x * sin;
  4857. result.y = axis.y * sin;
  4858. result.z = axis.z * sin;
  4859. return result;
  4860. };
  4861. /**
  4862. * Creates a new quaternion from data stored into an array
  4863. * @param array defines the data source
  4864. * @param offset defines the offset in the source array where the data starts
  4865. * @returns a new quaternion
  4866. */
  4867. Quaternion.FromArray = function (array, offset) {
  4868. if (!offset) {
  4869. offset = 0;
  4870. }
  4871. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4872. };
  4873. /**
  4874. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4875. * @param yaw defines the rotation around Y axis
  4876. * @param pitch defines the rotation around X axis
  4877. * @param roll defines the rotation around Z axis
  4878. * @returns the new quaternion
  4879. */
  4880. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4881. var q = new Quaternion();
  4882. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4883. return q;
  4884. };
  4885. /**
  4886. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4887. * @param yaw defines the rotation around Y axis
  4888. * @param pitch defines the rotation around X axis
  4889. * @param roll defines the rotation around Z axis
  4890. * @param result defines the target quaternion
  4891. */
  4892. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4893. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4894. var halfRoll = roll * 0.5;
  4895. var halfPitch = pitch * 0.5;
  4896. var halfYaw = yaw * 0.5;
  4897. var sinRoll = Math.sin(halfRoll);
  4898. var cosRoll = Math.cos(halfRoll);
  4899. var sinPitch = Math.sin(halfPitch);
  4900. var cosPitch = Math.cos(halfPitch);
  4901. var sinYaw = Math.sin(halfYaw);
  4902. var cosYaw = Math.cos(halfYaw);
  4903. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4904. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4905. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4906. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4907. };
  4908. /**
  4909. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4910. * @param alpha defines the rotation around first axis
  4911. * @param beta defines the rotation around second axis
  4912. * @param gamma defines the rotation around third axis
  4913. * @returns the new quaternion
  4914. */
  4915. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4916. var result = new Quaternion();
  4917. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4918. return result;
  4919. };
  4920. /**
  4921. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4922. * @param alpha defines the rotation around first axis
  4923. * @param beta defines the rotation around second axis
  4924. * @param gamma defines the rotation around third axis
  4925. * @param result defines the target quaternion
  4926. */
  4927. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4928. // Produces a quaternion from Euler angles in the z-x-z orientation
  4929. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4930. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4931. var halfBeta = beta * 0.5;
  4932. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4933. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4934. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4935. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4936. };
  4937. /**
  4938. * 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)
  4939. * @param axis1 defines the first axis
  4940. * @param axis2 defines the second axis
  4941. * @param axis3 defines the third axis
  4942. * @returns the new quaternion
  4943. */
  4944. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4945. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4946. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4947. return quat;
  4948. };
  4949. /**
  4950. * 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
  4951. * @param axis1 defines the first axis
  4952. * @param axis2 defines the second axis
  4953. * @param axis3 defines the third axis
  4954. * @param ref defines the target quaternion
  4955. */
  4956. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4957. var rotMat = MathTmp.Matrix[0];
  4958. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4959. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4960. };
  4961. /**
  4962. * Interpolates between two quaternions
  4963. * @param left defines first quaternion
  4964. * @param right defines second quaternion
  4965. * @param amount defines the gradient to use
  4966. * @returns the new interpolated quaternion
  4967. */
  4968. Quaternion.Slerp = function (left, right, amount) {
  4969. var result = Quaternion.Identity();
  4970. Quaternion.SlerpToRef(left, right, amount, result);
  4971. return result;
  4972. };
  4973. /**
  4974. * Interpolates between two quaternions and stores it into a target quaternion
  4975. * @param left defines first quaternion
  4976. * @param right defines second quaternion
  4977. * @param amount defines the gradient to use
  4978. * @param result defines the target quaternion
  4979. */
  4980. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4981. var num2;
  4982. var num3;
  4983. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4984. var flag = false;
  4985. if (num4 < 0) {
  4986. flag = true;
  4987. num4 = -num4;
  4988. }
  4989. if (num4 > 0.999999) {
  4990. num3 = 1 - amount;
  4991. num2 = flag ? -amount : amount;
  4992. }
  4993. else {
  4994. var num5 = Math.acos(num4);
  4995. var num6 = (1.0 / Math.sin(num5));
  4996. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4997. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4998. }
  4999. result.x = (num3 * left.x) + (num2 * right.x);
  5000. result.y = (num3 * left.y) + (num2 * right.y);
  5001. result.z = (num3 * left.z) + (num2 * right.z);
  5002. result.w = (num3 * left.w) + (num2 * right.w);
  5003. };
  5004. /**
  5005. * Interpolate between two quaternions using Hermite interpolation
  5006. * @param value1 defines first quaternion
  5007. * @param tangent1 defines the incoming tangent
  5008. * @param value2 defines second quaternion
  5009. * @param tangent2 defines the outgoing tangent
  5010. * @param amount defines the target quaternion
  5011. * @returns the new interpolated quaternion
  5012. */
  5013. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5014. var squared = amount * amount;
  5015. var cubed = amount * squared;
  5016. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5017. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5018. var part3 = (cubed - (2.0 * squared)) + amount;
  5019. var part4 = cubed - squared;
  5020. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5021. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5022. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5023. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5024. return new Quaternion(x, y, z, w);
  5025. };
  5026. return Quaternion;
  5027. }());
  5028. BABYLON.Quaternion = Quaternion;
  5029. /**
  5030. * Class used to store matrix data (4x4)
  5031. */
  5032. var Matrix = /** @class */ (function () {
  5033. /**
  5034. * Creates an empty matrix (filled with zeros)
  5035. */
  5036. function Matrix() {
  5037. this._isIdentity = false;
  5038. this._isIdentityDirty = true;
  5039. /**
  5040. * Gets or sets the internal data of the matrix
  5041. */
  5042. this.m = new Float32Array(16);
  5043. this._markAsUpdated();
  5044. }
  5045. /** @hidden */
  5046. Matrix.prototype._markAsUpdated = function () {
  5047. this.updateFlag = Matrix._updateFlagSeed++;
  5048. this._isIdentityDirty = true;
  5049. };
  5050. // Properties
  5051. /**
  5052. * Check if the current matrix is indentity
  5053. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5054. * @returns true is the matrix is the identity matrix
  5055. */
  5056. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5057. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5058. if (this._isIdentityDirty) {
  5059. this._isIdentityDirty = false;
  5060. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5061. this._isIdentity = false;
  5062. }
  5063. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5064. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5065. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5066. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5067. this._isIdentity = false;
  5068. }
  5069. else {
  5070. this._isIdentity = true;
  5071. }
  5072. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5073. this._isIdentity = false;
  5074. }
  5075. }
  5076. return this._isIdentity;
  5077. };
  5078. /**
  5079. * Gets the determinant of the matrix
  5080. * @returns the matrix determinant
  5081. */
  5082. Matrix.prototype.determinant = function () {
  5083. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5084. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5085. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5086. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5087. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5088. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5089. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5090. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5091. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5092. };
  5093. // Methods
  5094. /**
  5095. * Returns the matrix as a Float32Array
  5096. * @returns the matrix underlying array
  5097. */
  5098. Matrix.prototype.toArray = function () {
  5099. return this.m;
  5100. };
  5101. /**
  5102. * Returns the matrix as a Float32Array
  5103. * @returns the matrix underlying array.
  5104. */
  5105. Matrix.prototype.asArray = function () {
  5106. return this.toArray();
  5107. };
  5108. /**
  5109. * Inverts the current matrix in place
  5110. * @returns the current inverted matrix
  5111. */
  5112. Matrix.prototype.invert = function () {
  5113. this.invertToRef(this);
  5114. return this;
  5115. };
  5116. /**
  5117. * Sets all the matrix elements to zero
  5118. * @returns the current matrix
  5119. */
  5120. Matrix.prototype.reset = function () {
  5121. for (var index = 0; index < 16; index++) {
  5122. this.m[index] = 0.0;
  5123. }
  5124. this._markAsUpdated();
  5125. return this;
  5126. };
  5127. /**
  5128. * Adds the current matrix with a second one
  5129. * @param other defines the matrix to add
  5130. * @returns a new matrix as the addition of the current matrix and the given one
  5131. */
  5132. Matrix.prototype.add = function (other) {
  5133. var result = new Matrix();
  5134. this.addToRef(other, result);
  5135. return result;
  5136. };
  5137. /**
  5138. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5139. * @param other defines the matrix to add
  5140. * @param result defines the target matrix
  5141. * @returns the current matrix
  5142. */
  5143. Matrix.prototype.addToRef = function (other, result) {
  5144. for (var index = 0; index < 16; index++) {
  5145. result.m[index] = this.m[index] + other.m[index];
  5146. }
  5147. result._markAsUpdated();
  5148. return this;
  5149. };
  5150. /**
  5151. * Adds in place the given matrix to the current matrix
  5152. * @param other defines the second operand
  5153. * @returns the current updated matrix
  5154. */
  5155. Matrix.prototype.addToSelf = function (other) {
  5156. for (var index = 0; index < 16; index++) {
  5157. this.m[index] += other.m[index];
  5158. }
  5159. this._markAsUpdated();
  5160. return this;
  5161. };
  5162. /**
  5163. * Sets the given matrix to the current inverted Matrix
  5164. * @param other defines the target matrix
  5165. * @returns the unmodified current matrix
  5166. */
  5167. Matrix.prototype.invertToRef = function (other) {
  5168. var l1 = this.m[0];
  5169. var l2 = this.m[1];
  5170. var l3 = this.m[2];
  5171. var l4 = this.m[3];
  5172. var l5 = this.m[4];
  5173. var l6 = this.m[5];
  5174. var l7 = this.m[6];
  5175. var l8 = this.m[7];
  5176. var l9 = this.m[8];
  5177. var l10 = this.m[9];
  5178. var l11 = this.m[10];
  5179. var l12 = this.m[11];
  5180. var l13 = this.m[12];
  5181. var l14 = this.m[13];
  5182. var l15 = this.m[14];
  5183. var l16 = this.m[15];
  5184. var l17 = (l11 * l16) - (l12 * l15);
  5185. var l18 = (l10 * l16) - (l12 * l14);
  5186. var l19 = (l10 * l15) - (l11 * l14);
  5187. var l20 = (l9 * l16) - (l12 * l13);
  5188. var l21 = (l9 * l15) - (l11 * l13);
  5189. var l22 = (l9 * l14) - (l10 * l13);
  5190. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5191. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5192. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5193. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5194. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5195. var l28 = (l7 * l16) - (l8 * l15);
  5196. var l29 = (l6 * l16) - (l8 * l14);
  5197. var l30 = (l6 * l15) - (l7 * l14);
  5198. var l31 = (l5 * l16) - (l8 * l13);
  5199. var l32 = (l5 * l15) - (l7 * l13);
  5200. var l33 = (l5 * l14) - (l6 * l13);
  5201. var l34 = (l7 * l12) - (l8 * l11);
  5202. var l35 = (l6 * l12) - (l8 * l10);
  5203. var l36 = (l6 * l11) - (l7 * l10);
  5204. var l37 = (l5 * l12) - (l8 * l9);
  5205. var l38 = (l5 * l11) - (l7 * l9);
  5206. var l39 = (l5 * l10) - (l6 * l9);
  5207. other.m[0] = l23 * l27;
  5208. other.m[4] = l24 * l27;
  5209. other.m[8] = l25 * l27;
  5210. other.m[12] = l26 * l27;
  5211. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5212. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5213. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5214. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5215. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5216. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5217. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5218. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5219. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5220. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5221. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5222. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5223. other._markAsUpdated();
  5224. return this;
  5225. };
  5226. /**
  5227. * Inserts the translation vector (using 3 floats) in the current matrix
  5228. * @param x defines the 1st component of the translation
  5229. * @param y defines the 2nd component of the translation
  5230. * @param z defines the 3rd component of the translation
  5231. * @returns the current updated matrix
  5232. */
  5233. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5234. this.m[12] = x;
  5235. this.m[13] = y;
  5236. this.m[14] = z;
  5237. this._markAsUpdated();
  5238. return this;
  5239. };
  5240. /**
  5241. * Inserts the translation vector in the current matrix
  5242. * @param vector3 defines the translation to insert
  5243. * @returns the current updated matrix
  5244. */
  5245. Matrix.prototype.setTranslation = function (vector3) {
  5246. this.m[12] = vector3.x;
  5247. this.m[13] = vector3.y;
  5248. this.m[14] = vector3.z;
  5249. this._markAsUpdated();
  5250. return this;
  5251. };
  5252. /**
  5253. * Gets the translation value of the current matrix
  5254. * @returns a new Vector3 as the extracted translation from the matrix
  5255. */
  5256. Matrix.prototype.getTranslation = function () {
  5257. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5258. };
  5259. /**
  5260. * Fill a Vector3 with the extracted translation from the matrix
  5261. * @param result defines the Vector3 where to store the translation
  5262. * @returns the current matrix
  5263. */
  5264. Matrix.prototype.getTranslationToRef = function (result) {
  5265. result.x = this.m[12];
  5266. result.y = this.m[13];
  5267. result.z = this.m[14];
  5268. return this;
  5269. };
  5270. /**
  5271. * Remove rotation and scaling part from the matrix
  5272. * @returns the updated matrix
  5273. */
  5274. Matrix.prototype.removeRotationAndScaling = function () {
  5275. this.setRowFromFloats(0, 1, 0, 0, 0);
  5276. this.setRowFromFloats(1, 0, 1, 0, 0);
  5277. this.setRowFromFloats(2, 0, 0, 1, 0);
  5278. return this;
  5279. };
  5280. /**
  5281. * Multiply two matrices
  5282. * @param other defines the second operand
  5283. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5284. */
  5285. Matrix.prototype.multiply = function (other) {
  5286. var result = new Matrix();
  5287. this.multiplyToRef(other, result);
  5288. return result;
  5289. };
  5290. /**
  5291. * Copy the current matrix from the given one
  5292. * @param other defines the source matrix
  5293. * @returns the current updated matrix
  5294. */
  5295. Matrix.prototype.copyFrom = function (other) {
  5296. for (var index = 0; index < 16; index++) {
  5297. this.m[index] = other.m[index];
  5298. }
  5299. this._markAsUpdated();
  5300. return this;
  5301. };
  5302. /**
  5303. * Populates the given array from the starting index with the current matrix values
  5304. * @param array defines the target array
  5305. * @param offset defines the offset in the target array where to start storing values
  5306. * @returns the current matrix
  5307. */
  5308. Matrix.prototype.copyToArray = function (array, offset) {
  5309. if (offset === void 0) { offset = 0; }
  5310. for (var index = 0; index < 16; index++) {
  5311. array[offset + index] = this.m[index];
  5312. }
  5313. return this;
  5314. };
  5315. /**
  5316. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5317. * @param other defines the second operand
  5318. * @param result defines the matrix where to store the multiplication
  5319. * @returns the current matrix
  5320. */
  5321. Matrix.prototype.multiplyToRef = function (other, result) {
  5322. this.multiplyToArray(other, result.m, 0);
  5323. result._markAsUpdated();
  5324. return this;
  5325. };
  5326. /**
  5327. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5328. * @param other defines the second operand
  5329. * @param result defines the array where to store the multiplication
  5330. * @param offset defines the offset in the target array where to start storing values
  5331. * @returns the current matrix
  5332. */
  5333. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5334. var tm0 = this.m[0];
  5335. var tm1 = this.m[1];
  5336. var tm2 = this.m[2];
  5337. var tm3 = this.m[3];
  5338. var tm4 = this.m[4];
  5339. var tm5 = this.m[5];
  5340. var tm6 = this.m[6];
  5341. var tm7 = this.m[7];
  5342. var tm8 = this.m[8];
  5343. var tm9 = this.m[9];
  5344. var tm10 = this.m[10];
  5345. var tm11 = this.m[11];
  5346. var tm12 = this.m[12];
  5347. var tm13 = this.m[13];
  5348. var tm14 = this.m[14];
  5349. var tm15 = this.m[15];
  5350. var om0 = other.m[0];
  5351. var om1 = other.m[1];
  5352. var om2 = other.m[2];
  5353. var om3 = other.m[3];
  5354. var om4 = other.m[4];
  5355. var om5 = other.m[5];
  5356. var om6 = other.m[6];
  5357. var om7 = other.m[7];
  5358. var om8 = other.m[8];
  5359. var om9 = other.m[9];
  5360. var om10 = other.m[10];
  5361. var om11 = other.m[11];
  5362. var om12 = other.m[12];
  5363. var om13 = other.m[13];
  5364. var om14 = other.m[14];
  5365. var om15 = other.m[15];
  5366. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5367. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5368. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5369. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5370. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5371. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5372. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5373. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5374. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5375. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5376. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5377. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5378. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5379. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5380. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5381. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5382. return this;
  5383. };
  5384. /**
  5385. * Check equality between this matrix and a second one
  5386. * @param value defines the second matrix to compare
  5387. * @returns true is the current matrix and the given one values are strictly equal
  5388. */
  5389. Matrix.prototype.equals = function (value) {
  5390. return value &&
  5391. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5392. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5393. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5394. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5395. };
  5396. /**
  5397. * Clone the current matrix
  5398. * @returns a new matrix from the current matrix
  5399. */
  5400. Matrix.prototype.clone = function () {
  5401. 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]);
  5402. };
  5403. /**
  5404. * Returns the name of the current matrix class
  5405. * @returns the string "Matrix"
  5406. */
  5407. Matrix.prototype.getClassName = function () {
  5408. return "Matrix";
  5409. };
  5410. /**
  5411. * Gets the hash code of the current matrix
  5412. * @returns the hash code
  5413. */
  5414. Matrix.prototype.getHashCode = function () {
  5415. var hash = this.m[0] || 0;
  5416. for (var i = 1; i < 16; i++) {
  5417. hash = (hash * 397) ^ (this.m[i] || 0);
  5418. }
  5419. return hash;
  5420. };
  5421. /**
  5422. * Decomposes the current Matrix into a translation, rotation and scaling components
  5423. * @param scale defines the scale vector3 given as a reference to update
  5424. * @param rotation defines the rotation quaternion given as a reference to update
  5425. * @param translation defines the translation vector3 given as a reference to update
  5426. * @returns true if operation was successful
  5427. */
  5428. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5429. if (translation) {
  5430. translation.x = this.m[12];
  5431. translation.y = this.m[13];
  5432. translation.z = this.m[14];
  5433. }
  5434. scale = scale || MathTmp.Vector3[0];
  5435. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5436. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5437. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5438. if (this.determinant() <= 0) {
  5439. scale.y *= -1;
  5440. }
  5441. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5442. if (rotation) {
  5443. rotation.x = 0;
  5444. rotation.y = 0;
  5445. rotation.z = 0;
  5446. rotation.w = 1;
  5447. }
  5448. return false;
  5449. }
  5450. if (rotation) {
  5451. 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]);
  5452. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5453. }
  5454. return true;
  5455. };
  5456. /**
  5457. * Gets specific row of the matrix
  5458. * @param index defines the number of the row to get
  5459. * @returns the index-th row of the current matrix as a new Vector4
  5460. */
  5461. Matrix.prototype.getRow = function (index) {
  5462. if (index < 0 || index > 3) {
  5463. return null;
  5464. }
  5465. var i = index * 4;
  5466. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5467. };
  5468. /**
  5469. * Sets the index-th row of the current matrix to the vector4 values
  5470. * @param index defines the number of the row to set
  5471. * @param row defines the target vector4
  5472. * @returns the updated current matrix
  5473. */
  5474. Matrix.prototype.setRow = function (index, row) {
  5475. if (index < 0 || index > 3) {
  5476. return this;
  5477. }
  5478. var i = index * 4;
  5479. this.m[i + 0] = row.x;
  5480. this.m[i + 1] = row.y;
  5481. this.m[i + 2] = row.z;
  5482. this.m[i + 3] = row.w;
  5483. this._markAsUpdated();
  5484. return this;
  5485. };
  5486. /**
  5487. * Compute the transpose of the matrix
  5488. * @returns the new transposed matrix
  5489. */
  5490. Matrix.prototype.transpose = function () {
  5491. return Matrix.Transpose(this);
  5492. };
  5493. /**
  5494. * Compute the transpose of the matrix and store it in a given matrix
  5495. * @param result defines the target matrix
  5496. * @returns the current matrix
  5497. */
  5498. Matrix.prototype.transposeToRef = function (result) {
  5499. Matrix.TransposeToRef(this, result);
  5500. return this;
  5501. };
  5502. /**
  5503. * Sets the index-th row of the current matrix with the given 4 x float values
  5504. * @param index defines the row index
  5505. * @param x defines the x component to set
  5506. * @param y defines the y component to set
  5507. * @param z defines the z component to set
  5508. * @param w defines the w component to set
  5509. * @returns the updated current matrix
  5510. */
  5511. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5512. if (index < 0 || index > 3) {
  5513. return this;
  5514. }
  5515. var i = index * 4;
  5516. this.m[i + 0] = x;
  5517. this.m[i + 1] = y;
  5518. this.m[i + 2] = z;
  5519. this.m[i + 3] = w;
  5520. this._markAsUpdated();
  5521. return this;
  5522. };
  5523. /**
  5524. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5525. * @param scale defines the scale factor
  5526. * @returns a new matrix
  5527. */
  5528. Matrix.prototype.scale = function (scale) {
  5529. var result = new Matrix();
  5530. this.scaleToRef(scale, result);
  5531. return result;
  5532. };
  5533. /**
  5534. * Scale the current matrix values by a factor to a given result matrix
  5535. * @param scale defines the scale factor
  5536. * @param result defines the matrix to store the result
  5537. * @returns the current matrix
  5538. */
  5539. Matrix.prototype.scaleToRef = function (scale, result) {
  5540. for (var index = 0; index < 16; index++) {
  5541. result.m[index] = this.m[index] * scale;
  5542. }
  5543. result._markAsUpdated();
  5544. return this;
  5545. };
  5546. /**
  5547. * Scale the current matrix values by a factor and add the result to a given matrix
  5548. * @param scale defines the scale factor
  5549. * @param result defines the Matrix to store the result
  5550. * @returns the current matrix
  5551. */
  5552. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5553. for (var index = 0; index < 16; index++) {
  5554. result.m[index] += this.m[index] * scale;
  5555. }
  5556. result._markAsUpdated();
  5557. return this;
  5558. };
  5559. /**
  5560. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5561. * @param ref matrix to store the result
  5562. */
  5563. Matrix.prototype.toNormalMatrix = function (ref) {
  5564. this.invertToRef(ref);
  5565. ref.transpose();
  5566. var m = ref.m;
  5567. 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);
  5568. };
  5569. /**
  5570. * Gets only rotation part of the current matrix
  5571. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5572. */
  5573. Matrix.prototype.getRotationMatrix = function () {
  5574. var result = Matrix.Identity();
  5575. this.getRotationMatrixToRef(result);
  5576. return result;
  5577. };
  5578. /**
  5579. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5580. * @param result defines the target matrix to store data to
  5581. * @returns the current matrix
  5582. */
  5583. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5584. var m = this.m;
  5585. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5586. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5587. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5588. if (this.determinant() <= 0) {
  5589. sy *= -1;
  5590. }
  5591. if (sx === 0 || sy === 0 || sz === 0) {
  5592. Matrix.IdentityToRef(result);
  5593. }
  5594. else {
  5595. 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);
  5596. }
  5597. return this;
  5598. };
  5599. // Statics
  5600. /**
  5601. * Creates a matrix from an array
  5602. * @param array defines the source array
  5603. * @param offset defines an offset in the source array
  5604. * @returns a new Matrix set from the starting index of the given array
  5605. */
  5606. Matrix.FromArray = function (array, offset) {
  5607. var result = new Matrix();
  5608. if (!offset) {
  5609. offset = 0;
  5610. }
  5611. Matrix.FromArrayToRef(array, offset, result);
  5612. return result;
  5613. };
  5614. /**
  5615. * Copy the content of an array into a given matrix
  5616. * @param array defines the source array
  5617. * @param offset defines an offset in the source array
  5618. * @param result defines the target matrix
  5619. */
  5620. Matrix.FromArrayToRef = function (array, offset, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] = array[index + offset];
  5623. }
  5624. result._markAsUpdated();
  5625. };
  5626. /**
  5627. * Stores an array into a matrix after having multiplied each component by a given factor
  5628. * @param array defines the source array
  5629. * @param offset defines the offset in the source array
  5630. * @param scale defines the scaling factor
  5631. * @param result defines the target matrix
  5632. */
  5633. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5634. for (var index = 0; index < 16; index++) {
  5635. result.m[index] = array[index + offset] * scale;
  5636. }
  5637. result._markAsUpdated();
  5638. };
  5639. /**
  5640. * Stores a list of values (16) inside a given matrix
  5641. * @param initialM11 defines 1st value of 1st row
  5642. * @param initialM12 defines 2nd value of 1st row
  5643. * @param initialM13 defines 3rd value of 1st row
  5644. * @param initialM14 defines 4th value of 1st row
  5645. * @param initialM21 defines 1st value of 2nd row
  5646. * @param initialM22 defines 2nd value of 2nd row
  5647. * @param initialM23 defines 3rd value of 2nd row
  5648. * @param initialM24 defines 4th value of 2nd row
  5649. * @param initialM31 defines 1st value of 3rd row
  5650. * @param initialM32 defines 2nd value of 3rd row
  5651. * @param initialM33 defines 3rd value of 3rd row
  5652. * @param initialM34 defines 4th value of 3rd row
  5653. * @param initialM41 defines 1st value of 4th row
  5654. * @param initialM42 defines 2nd value of 4th row
  5655. * @param initialM43 defines 3rd value of 4th row
  5656. * @param initialM44 defines 4th value of 4th row
  5657. * @param result defines the target matrix
  5658. */
  5659. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5660. result.m[0] = initialM11;
  5661. result.m[1] = initialM12;
  5662. result.m[2] = initialM13;
  5663. result.m[3] = initialM14;
  5664. result.m[4] = initialM21;
  5665. result.m[5] = initialM22;
  5666. result.m[6] = initialM23;
  5667. result.m[7] = initialM24;
  5668. result.m[8] = initialM31;
  5669. result.m[9] = initialM32;
  5670. result.m[10] = initialM33;
  5671. result.m[11] = initialM34;
  5672. result.m[12] = initialM41;
  5673. result.m[13] = initialM42;
  5674. result.m[14] = initialM43;
  5675. result.m[15] = initialM44;
  5676. result._markAsUpdated();
  5677. };
  5678. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5679. /**
  5680. * Gets an identity matrix that must not be updated
  5681. */
  5682. get: function () {
  5683. return Matrix._identityReadOnly;
  5684. },
  5685. enumerable: true,
  5686. configurable: true
  5687. });
  5688. /**
  5689. * Creates new matrix from a list of values (16)
  5690. * @param initialM11 defines 1st value of 1st row
  5691. * @param initialM12 defines 2nd value of 1st row
  5692. * @param initialM13 defines 3rd value of 1st row
  5693. * @param initialM14 defines 4th value of 1st row
  5694. * @param initialM21 defines 1st value of 2nd row
  5695. * @param initialM22 defines 2nd value of 2nd row
  5696. * @param initialM23 defines 3rd value of 2nd row
  5697. * @param initialM24 defines 4th value of 2nd row
  5698. * @param initialM31 defines 1st value of 3rd row
  5699. * @param initialM32 defines 2nd value of 3rd row
  5700. * @param initialM33 defines 3rd value of 3rd row
  5701. * @param initialM34 defines 4th value of 3rd row
  5702. * @param initialM41 defines 1st value of 4th row
  5703. * @param initialM42 defines 2nd value of 4th row
  5704. * @param initialM43 defines 3rd value of 4th row
  5705. * @param initialM44 defines 4th value of 4th row
  5706. * @returns the new matrix
  5707. */
  5708. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5709. var result = new Matrix();
  5710. result.m[0] = initialM11;
  5711. result.m[1] = initialM12;
  5712. result.m[2] = initialM13;
  5713. result.m[3] = initialM14;
  5714. result.m[4] = initialM21;
  5715. result.m[5] = initialM22;
  5716. result.m[6] = initialM23;
  5717. result.m[7] = initialM24;
  5718. result.m[8] = initialM31;
  5719. result.m[9] = initialM32;
  5720. result.m[10] = initialM33;
  5721. result.m[11] = initialM34;
  5722. result.m[12] = initialM41;
  5723. result.m[13] = initialM42;
  5724. result.m[14] = initialM43;
  5725. result.m[15] = initialM44;
  5726. return result;
  5727. };
  5728. /**
  5729. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5730. * @param scale defines the scale vector3
  5731. * @param rotation defines the rotation quaternion
  5732. * @param translation defines the translation vector3
  5733. * @returns a new matrix
  5734. */
  5735. Matrix.Compose = function (scale, rotation, translation) {
  5736. var result = Matrix.Identity();
  5737. Matrix.ComposeToRef(scale, rotation, translation, result);
  5738. return result;
  5739. };
  5740. /**
  5741. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5742. * @param scale defines the scale vector3
  5743. * @param rotation defines the rotation quaternion
  5744. * @param translation defines the translation vector3
  5745. * @param result defines the target matrix
  5746. */
  5747. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5748. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5749. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5750. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5751. result.setTranslation(translation);
  5752. };
  5753. /**
  5754. * Creates a new identity matrix
  5755. * @returns a new identity matrix
  5756. */
  5757. Matrix.Identity = function () {
  5758. 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);
  5759. };
  5760. /**
  5761. * Creates a new identity matrix and stores the result in a given matrix
  5762. * @param result defines the target matrix
  5763. */
  5764. Matrix.IdentityToRef = function (result) {
  5765. 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);
  5766. };
  5767. /**
  5768. * Creates a new zero matrix
  5769. * @returns a new zero matrix
  5770. */
  5771. Matrix.Zero = function () {
  5772. 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);
  5773. };
  5774. /**
  5775. * Creates a new rotation matrix for "angle" radians around the X axis
  5776. * @param angle defines the angle (in radians) to use
  5777. * @return the new matrix
  5778. */
  5779. Matrix.RotationX = function (angle) {
  5780. var result = new Matrix();
  5781. Matrix.RotationXToRef(angle, result);
  5782. return result;
  5783. };
  5784. /**
  5785. * Creates a new matrix as the invert of a given matrix
  5786. * @param source defines the source matrix
  5787. * @returns the new matrix
  5788. */
  5789. Matrix.Invert = function (source) {
  5790. var result = new Matrix();
  5791. source.invertToRef(result);
  5792. return result;
  5793. };
  5794. /**
  5795. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5796. * @param angle defines the angle (in radians) to use
  5797. * @param result defines the target matrix
  5798. */
  5799. Matrix.RotationXToRef = function (angle, result) {
  5800. var s = Math.sin(angle);
  5801. var c = Math.cos(angle);
  5802. result.m[0] = 1.0;
  5803. result.m[15] = 1.0;
  5804. result.m[5] = c;
  5805. result.m[10] = c;
  5806. result.m[9] = -s;
  5807. result.m[6] = s;
  5808. result.m[1] = 0.0;
  5809. result.m[2] = 0.0;
  5810. result.m[3] = 0.0;
  5811. result.m[4] = 0.0;
  5812. result.m[7] = 0.0;
  5813. result.m[8] = 0.0;
  5814. result.m[11] = 0.0;
  5815. result.m[12] = 0.0;
  5816. result.m[13] = 0.0;
  5817. result.m[14] = 0.0;
  5818. result._markAsUpdated();
  5819. };
  5820. /**
  5821. * Creates a new rotation matrix for "angle" radians around the Y axis
  5822. * @param angle defines the angle (in radians) to use
  5823. * @return the new matrix
  5824. */
  5825. Matrix.RotationY = function (angle) {
  5826. var result = new Matrix();
  5827. Matrix.RotationYToRef(angle, result);
  5828. return result;
  5829. };
  5830. /**
  5831. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5832. * @param angle defines the angle (in radians) to use
  5833. * @param result defines the target matrix
  5834. */
  5835. Matrix.RotationYToRef = function (angle, result) {
  5836. var s = Math.sin(angle);
  5837. var c = Math.cos(angle);
  5838. result.m[5] = 1.0;
  5839. result.m[15] = 1.0;
  5840. result.m[0] = c;
  5841. result.m[2] = -s;
  5842. result.m[8] = s;
  5843. result.m[10] = c;
  5844. result.m[1] = 0.0;
  5845. result.m[3] = 0.0;
  5846. result.m[4] = 0.0;
  5847. result.m[6] = 0.0;
  5848. result.m[7] = 0.0;
  5849. result.m[9] = 0.0;
  5850. result.m[11] = 0.0;
  5851. result.m[12] = 0.0;
  5852. result.m[13] = 0.0;
  5853. result.m[14] = 0.0;
  5854. result._markAsUpdated();
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the Z axis
  5858. * @param angle defines the angle (in radians) to use
  5859. * @return the new matrix
  5860. */
  5861. Matrix.RotationZ = function (angle) {
  5862. var result = new Matrix();
  5863. Matrix.RotationZToRef(angle, result);
  5864. return result;
  5865. };
  5866. /**
  5867. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5868. * @param angle defines the angle (in radians) to use
  5869. * @param result defines the target matrix
  5870. */
  5871. Matrix.RotationZToRef = function (angle, result) {
  5872. var s = Math.sin(angle);
  5873. var c = Math.cos(angle);
  5874. result.m[10] = 1.0;
  5875. result.m[15] = 1.0;
  5876. result.m[0] = c;
  5877. result.m[1] = s;
  5878. result.m[4] = -s;
  5879. result.m[5] = c;
  5880. result.m[2] = 0.0;
  5881. result.m[3] = 0.0;
  5882. result.m[6] = 0.0;
  5883. result.m[7] = 0.0;
  5884. result.m[8] = 0.0;
  5885. result.m[9] = 0.0;
  5886. result.m[11] = 0.0;
  5887. result.m[12] = 0.0;
  5888. result.m[13] = 0.0;
  5889. result.m[14] = 0.0;
  5890. result._markAsUpdated();
  5891. };
  5892. /**
  5893. * Creates a new rotation matrix for "angle" radians around the given axis
  5894. * @param axis defines the axis to use
  5895. * @param angle defines the angle (in radians) to use
  5896. * @return the new matrix
  5897. */
  5898. Matrix.RotationAxis = function (axis, angle) {
  5899. var result = Matrix.Zero();
  5900. Matrix.RotationAxisToRef(axis, angle, result);
  5901. return result;
  5902. };
  5903. /**
  5904. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5905. * @param axis defines the axis to use
  5906. * @param angle defines the angle (in radians) to use
  5907. * @param result defines the target matrix
  5908. */
  5909. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5910. var s = Math.sin(-angle);
  5911. var c = Math.cos(-angle);
  5912. var c1 = 1 - c;
  5913. axis.normalize();
  5914. result.m[0] = (axis.x * axis.x) * c1 + c;
  5915. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5916. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5917. result.m[3] = 0.0;
  5918. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5919. result.m[5] = (axis.y * axis.y) * c1 + c;
  5920. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5921. result.m[7] = 0.0;
  5922. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5923. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5924. result.m[10] = (axis.z * axis.z) * c1 + c;
  5925. result.m[11] = 0.0;
  5926. result.m[15] = 1.0;
  5927. result._markAsUpdated();
  5928. };
  5929. /**
  5930. * Creates a rotation matrix
  5931. * @param yaw defines the yaw angle in radians (Y axis)
  5932. * @param pitch defines the pitch angle in radians (X axis)
  5933. * @param roll defines the roll angle in radians (X axis)
  5934. * @returns the new rotation matrix
  5935. */
  5936. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5937. var result = new Matrix();
  5938. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5939. return result;
  5940. };
  5941. /**
  5942. * Creates a rotation matrix and stores it in a given matrix
  5943. * @param yaw defines the yaw angle in radians (Y axis)
  5944. * @param pitch defines the pitch angle in radians (X axis)
  5945. * @param roll defines the roll angle in radians (X axis)
  5946. * @param result defines the target matrix
  5947. */
  5948. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5949. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5950. this._tempQuaternion.toRotationMatrix(result);
  5951. };
  5952. /**
  5953. * Creates a scaling matrix
  5954. * @param x defines the scale factor on X axis
  5955. * @param y defines the scale factor on Y axis
  5956. * @param z defines the scale factor on Z axis
  5957. * @returns the new matrix
  5958. */
  5959. Matrix.Scaling = function (x, y, z) {
  5960. var result = Matrix.Zero();
  5961. Matrix.ScalingToRef(x, y, z, result);
  5962. return result;
  5963. };
  5964. /**
  5965. * Creates a scaling matrix and stores it in a given matrix
  5966. * @param x defines the scale factor on X axis
  5967. * @param y defines the scale factor on Y axis
  5968. * @param z defines the scale factor on Z axis
  5969. * @param result defines the target matrix
  5970. */
  5971. Matrix.ScalingToRef = function (x, y, z, result) {
  5972. result.m[0] = x;
  5973. result.m[1] = 0.0;
  5974. result.m[2] = 0.0;
  5975. result.m[3] = 0.0;
  5976. result.m[4] = 0.0;
  5977. result.m[5] = y;
  5978. result.m[6] = 0.0;
  5979. result.m[7] = 0.0;
  5980. result.m[8] = 0.0;
  5981. result.m[9] = 0.0;
  5982. result.m[10] = z;
  5983. result.m[11] = 0.0;
  5984. result.m[12] = 0.0;
  5985. result.m[13] = 0.0;
  5986. result.m[14] = 0.0;
  5987. result.m[15] = 1.0;
  5988. result._markAsUpdated();
  5989. };
  5990. /**
  5991. * Creates a translation matrix
  5992. * @param x defines the translation on X axis
  5993. * @param y defines the translation on Y axis
  5994. * @param z defines the translationon Z axis
  5995. * @returns the new matrix
  5996. */
  5997. Matrix.Translation = function (x, y, z) {
  5998. var result = Matrix.Identity();
  5999. Matrix.TranslationToRef(x, y, z, result);
  6000. return result;
  6001. };
  6002. /**
  6003. * Creates a translation matrix and stores it in a given matrix
  6004. * @param x defines the translation on X axis
  6005. * @param y defines the translation on Y axis
  6006. * @param z defines the translationon Z axis
  6007. * @param result defines the target matrix
  6008. */
  6009. Matrix.TranslationToRef = function (x, y, z, result) {
  6010. 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);
  6011. };
  6012. /**
  6013. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6014. * @param startValue defines the start value
  6015. * @param endValue defines the end value
  6016. * @param gradient defines the gradient factor
  6017. * @returns the new matrix
  6018. */
  6019. Matrix.Lerp = function (startValue, endValue, gradient) {
  6020. var result = Matrix.Zero();
  6021. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6022. return result;
  6023. };
  6024. /**
  6025. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6026. * @param startValue defines the start value
  6027. * @param endValue defines the end value
  6028. * @param gradient defines the gradient factor
  6029. * @param result defines the Matrix object where to store data
  6030. */
  6031. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6032. for (var index = 0; index < 16; index++) {
  6033. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6034. }
  6035. result._markAsUpdated();
  6036. };
  6037. /**
  6038. * Builds a new matrix whose values are computed by:
  6039. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6040. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6041. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6042. * @param startValue defines the first matrix
  6043. * @param endValue defines the second matrix
  6044. * @param gradient defines the gradient between the two matrices
  6045. * @returns the new matrix
  6046. */
  6047. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6048. var result = Matrix.Zero();
  6049. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6050. return result;
  6051. };
  6052. /**
  6053. * Update a matrix to values which are computed by:
  6054. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6055. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6056. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6057. * @param startValue defines the first matrix
  6058. * @param endValue defines the second matrix
  6059. * @param gradient defines the gradient between the two matrices
  6060. * @param result defines the target matrix
  6061. */
  6062. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6063. var startScale = MathTmp.Vector3[0];
  6064. var startRotation = MathTmp.Quaternion[0];
  6065. var startTranslation = MathTmp.Vector3[1];
  6066. startValue.decompose(startScale, startRotation, startTranslation);
  6067. var endScale = MathTmp.Vector3[2];
  6068. var endRotation = MathTmp.Quaternion[1];
  6069. var endTranslation = MathTmp.Vector3[3];
  6070. endValue.decompose(endScale, endRotation, endTranslation);
  6071. var resultScale = MathTmp.Vector3[4];
  6072. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6073. var resultRotation = MathTmp.Quaternion[2];
  6074. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6075. var resultTranslation = MathTmp.Vector3[5];
  6076. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6077. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6078. };
  6079. /**
  6080. * 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"
  6081. * This function works in left handed mode
  6082. * @param eye defines the final position of the entity
  6083. * @param target defines where the entity should look at
  6084. * @param up defines the up vector for the entity
  6085. * @returns the new matrix
  6086. */
  6087. Matrix.LookAtLH = function (eye, target, up) {
  6088. var result = Matrix.Zero();
  6089. Matrix.LookAtLHToRef(eye, target, up, result);
  6090. return result;
  6091. };
  6092. /**
  6093. * 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".
  6094. * This function works in left handed mode
  6095. * @param eye defines the final position of the entity
  6096. * @param target defines where the entity should look at
  6097. * @param up defines the up vector for the entity
  6098. * @param result defines the target matrix
  6099. */
  6100. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6101. // Z axis
  6102. target.subtractToRef(eye, this._zAxis);
  6103. this._zAxis.normalize();
  6104. // X axis
  6105. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6106. if (this._xAxis.lengthSquared() === 0) {
  6107. this._xAxis.x = 1.0;
  6108. }
  6109. else {
  6110. this._xAxis.normalize();
  6111. }
  6112. // Y axis
  6113. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6114. this._yAxis.normalize();
  6115. // Eye angles
  6116. var ex = -Vector3.Dot(this._xAxis, eye);
  6117. var ey = -Vector3.Dot(this._yAxis, eye);
  6118. var ez = -Vector3.Dot(this._zAxis, eye);
  6119. 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);
  6120. };
  6121. /**
  6122. * 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"
  6123. * This function works in right handed mode
  6124. * @param eye defines the final position of the entity
  6125. * @param target defines where the entity should look at
  6126. * @param up defines the up vector for the entity
  6127. * @returns the new matrix
  6128. */
  6129. Matrix.LookAtRH = function (eye, target, up) {
  6130. var result = Matrix.Zero();
  6131. Matrix.LookAtRHToRef(eye, target, up, result);
  6132. return result;
  6133. };
  6134. /**
  6135. * 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".
  6136. * This function works in right handed mode
  6137. * @param eye defines the final position of the entity
  6138. * @param target defines where the entity should look at
  6139. * @param up defines the up vector for the entity
  6140. * @param result defines the target matrix
  6141. */
  6142. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6143. // Z axis
  6144. eye.subtractToRef(target, this._zAxis);
  6145. this._zAxis.normalize();
  6146. // X axis
  6147. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6148. if (this._xAxis.lengthSquared() === 0) {
  6149. this._xAxis.x = 1.0;
  6150. }
  6151. else {
  6152. this._xAxis.normalize();
  6153. }
  6154. // Y axis
  6155. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6156. this._yAxis.normalize();
  6157. // Eye angles
  6158. var ex = -Vector3.Dot(this._xAxis, eye);
  6159. var ey = -Vector3.Dot(this._yAxis, eye);
  6160. var ez = -Vector3.Dot(this._zAxis, eye);
  6161. 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);
  6162. };
  6163. /**
  6164. * Create a left-handed orthographic projection matrix
  6165. * @param width defines the viewport width
  6166. * @param height defines the viewport height
  6167. * @param znear defines the near clip plane
  6168. * @param zfar defines the far clip plane
  6169. * @returns a new matrix as a left-handed orthographic projection matrix
  6170. */
  6171. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6172. var matrix = Matrix.Zero();
  6173. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6174. return matrix;
  6175. };
  6176. /**
  6177. * Store a left-handed orthographic projection to a given matrix
  6178. * @param width defines the viewport width
  6179. * @param height defines the viewport height
  6180. * @param znear defines the near clip plane
  6181. * @param zfar defines the far clip plane
  6182. * @param result defines the target matrix
  6183. */
  6184. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6185. var n = znear;
  6186. var f = zfar;
  6187. var a = 2.0 / width;
  6188. var b = 2.0 / height;
  6189. var c = 2.0 / (f - n);
  6190. var d = -(f + n) / (f - n);
  6191. 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);
  6192. };
  6193. /**
  6194. * Create a left-handed orthographic projection matrix
  6195. * @param left defines the viewport left coordinate
  6196. * @param right defines the viewport right coordinate
  6197. * @param bottom defines the viewport bottom coordinate
  6198. * @param top defines the viewport top coordinate
  6199. * @param znear defines the near clip plane
  6200. * @param zfar defines the far clip plane
  6201. * @returns a new matrix as a left-handed orthographic projection matrix
  6202. */
  6203. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6204. var matrix = Matrix.Zero();
  6205. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6206. return matrix;
  6207. };
  6208. /**
  6209. * Stores a left-handed orthographic projection into a given matrix
  6210. * @param left defines the viewport left coordinate
  6211. * @param right defines the viewport right coordinate
  6212. * @param bottom defines the viewport bottom coordinate
  6213. * @param top defines the viewport top coordinate
  6214. * @param znear defines the near clip plane
  6215. * @param zfar defines the far clip plane
  6216. * @param result defines the target matrix
  6217. */
  6218. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6219. var n = znear;
  6220. var f = zfar;
  6221. var a = 2.0 / (right - left);
  6222. var b = 2.0 / (top - bottom);
  6223. var c = 2.0 / (f - n);
  6224. var d = -(f + n) / (f - n);
  6225. var i0 = (left + right) / (left - right);
  6226. var i1 = (top + bottom) / (bottom - top);
  6227. 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);
  6228. };
  6229. /**
  6230. * Creates a right-handed orthographic projection matrix
  6231. * @param left defines the viewport left coordinate
  6232. * @param right defines the viewport right coordinate
  6233. * @param bottom defines the viewport bottom coordinate
  6234. * @param top defines the viewport top coordinate
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a right-handed orthographic projection matrix
  6238. */
  6239. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6242. return matrix;
  6243. };
  6244. /**
  6245. * Stores a right-handed orthographic projection into a given matrix
  6246. * @param left defines the viewport left coordinate
  6247. * @param right defines the viewport right coordinate
  6248. * @param bottom defines the viewport bottom coordinate
  6249. * @param top defines the viewport top coordinate
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @param result defines the target matrix
  6253. */
  6254. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6255. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6256. result.m[10] *= -1.0;
  6257. };
  6258. /**
  6259. * Creates a left-handed perspective projection matrix
  6260. * @param width defines the viewport width
  6261. * @param height defines the viewport height
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @returns a new matrix as a left-handed perspective projection matrix
  6265. */
  6266. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6267. var matrix = Matrix.Zero();
  6268. var n = znear;
  6269. var f = zfar;
  6270. var a = 2.0 * n / width;
  6271. var b = 2.0 * n / height;
  6272. var c = (f + n) / (f - n);
  6273. var d = -2.0 * f * n / (f - n);
  6274. 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);
  6275. return matrix;
  6276. };
  6277. /**
  6278. * Creates a left-handed perspective projection matrix
  6279. * @param fov defines the horizontal field of view
  6280. * @param aspect defines the aspect ratio
  6281. * @param znear defines the near clip plane
  6282. * @param zfar defines the far clip plane
  6283. * @returns a new matrix as a left-handed perspective projection matrix
  6284. */
  6285. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6286. var matrix = Matrix.Zero();
  6287. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6288. return matrix;
  6289. };
  6290. /**
  6291. * Stores a left-handed perspective projection into a given matrix
  6292. * @param fov defines the horizontal field of view
  6293. * @param aspect defines the aspect ratio
  6294. * @param znear defines the near clip plane
  6295. * @param zfar defines the far clip plane
  6296. * @param result defines the target matrix
  6297. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6298. */
  6299. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6300. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6301. var n = znear;
  6302. var f = zfar;
  6303. var t = 1.0 / (Math.tan(fov * 0.5));
  6304. var a = isVerticalFovFixed ? (t / aspect) : t;
  6305. var b = isVerticalFovFixed ? t : (t * aspect);
  6306. var c = (f + n) / (f - n);
  6307. var d = -2.0 * f * n / (f - n);
  6308. 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);
  6309. };
  6310. /**
  6311. * Creates a right-handed perspective projection matrix
  6312. * @param fov defines the horizontal field of view
  6313. * @param aspect defines the aspect ratio
  6314. * @param znear defines the near clip plane
  6315. * @param zfar defines the far clip plane
  6316. * @returns a new matrix as a right-handed perspective projection matrix
  6317. */
  6318. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6319. var matrix = Matrix.Zero();
  6320. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6321. return matrix;
  6322. };
  6323. /**
  6324. * Stores a right-handed perspective projection into a given matrix
  6325. * @param fov defines the horizontal field of view
  6326. * @param aspect defines the aspect ratio
  6327. * @param znear defines the near clip plane
  6328. * @param zfar defines the far clip plane
  6329. * @param result defines the target matrix
  6330. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6331. */
  6332. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6333. //alternatively this could be expressed as:
  6334. // m = PerspectiveFovLHToRef
  6335. // m[10] *= -1.0;
  6336. // m[11] *= -1.0;
  6337. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6338. var n = znear;
  6339. var f = zfar;
  6340. var t = 1.0 / (Math.tan(fov * 0.5));
  6341. var a = isVerticalFovFixed ? (t / aspect) : t;
  6342. var b = isVerticalFovFixed ? t : (t * aspect);
  6343. var c = -(f + n) / (f - n);
  6344. var d = -2 * f * n / (f - n);
  6345. 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);
  6346. };
  6347. /**
  6348. * Stores a perspective projection for WebVR info a given matrix
  6349. * @param fov defines the field of view
  6350. * @param znear defines the near clip plane
  6351. * @param zfar defines the far clip plane
  6352. * @param result defines the target matrix
  6353. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6354. */
  6355. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6356. if (rightHanded === void 0) { rightHanded = false; }
  6357. var rightHandedFactor = rightHanded ? -1 : 1;
  6358. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6359. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6360. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6361. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6362. var xScale = 2.0 / (leftTan + rightTan);
  6363. var yScale = 2.0 / (upTan + downTan);
  6364. result.m[0] = xScale;
  6365. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6366. result.m[5] = yScale;
  6367. result.m[6] = result.m[7] = 0.0;
  6368. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6369. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6370. result.m[10] = -zfar / (znear - zfar);
  6371. result.m[11] = 1.0 * rightHandedFactor;
  6372. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6373. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6374. result._markAsUpdated();
  6375. };
  6376. /**
  6377. * Computes a complete transformation matrix
  6378. * @param viewport defines the viewport to use
  6379. * @param world defines the world matrix
  6380. * @param view defines the view matrix
  6381. * @param projection defines the projection matrix
  6382. * @param zmin defines the near clip plane
  6383. * @param zmax defines the far clip plane
  6384. * @returns the transformation matrix
  6385. */
  6386. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6387. var cw = viewport.width;
  6388. var ch = viewport.height;
  6389. var cx = viewport.x;
  6390. var cy = viewport.y;
  6391. 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);
  6392. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6393. };
  6394. /**
  6395. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6396. * @param matrix defines the matrix to use
  6397. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6398. */
  6399. Matrix.GetAsMatrix2x2 = function (matrix) {
  6400. return new Float32Array([
  6401. matrix.m[0], matrix.m[1],
  6402. matrix.m[4], matrix.m[5]
  6403. ]);
  6404. };
  6405. /**
  6406. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6407. * @param matrix defines the matrix to use
  6408. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6409. */
  6410. Matrix.GetAsMatrix3x3 = function (matrix) {
  6411. return new Float32Array([
  6412. matrix.m[0], matrix.m[1], matrix.m[2],
  6413. matrix.m[4], matrix.m[5], matrix.m[6],
  6414. matrix.m[8], matrix.m[9], matrix.m[10]
  6415. ]);
  6416. };
  6417. /**
  6418. * Compute the transpose of a given matrix
  6419. * @param matrix defines the matrix to transpose
  6420. * @returns the new matrix
  6421. */
  6422. Matrix.Transpose = function (matrix) {
  6423. var result = new Matrix();
  6424. Matrix.TransposeToRef(matrix, result);
  6425. return result;
  6426. };
  6427. /**
  6428. * Compute the transpose of a matrix and store it in a target matrix
  6429. * @param matrix defines the matrix to transpose
  6430. * @param result defines the target matrix
  6431. */
  6432. Matrix.TransposeToRef = function (matrix, result) {
  6433. result.m[0] = matrix.m[0];
  6434. result.m[1] = matrix.m[4];
  6435. result.m[2] = matrix.m[8];
  6436. result.m[3] = matrix.m[12];
  6437. result.m[4] = matrix.m[1];
  6438. result.m[5] = matrix.m[5];
  6439. result.m[6] = matrix.m[9];
  6440. result.m[7] = matrix.m[13];
  6441. result.m[8] = matrix.m[2];
  6442. result.m[9] = matrix.m[6];
  6443. result.m[10] = matrix.m[10];
  6444. result.m[11] = matrix.m[14];
  6445. result.m[12] = matrix.m[3];
  6446. result.m[13] = matrix.m[7];
  6447. result.m[14] = matrix.m[11];
  6448. result.m[15] = matrix.m[15];
  6449. };
  6450. /**
  6451. * Computes a reflection matrix from a plane
  6452. * @param plane defines the reflection plane
  6453. * @returns a new matrix
  6454. */
  6455. Matrix.Reflection = function (plane) {
  6456. var matrix = new Matrix();
  6457. Matrix.ReflectionToRef(plane, matrix);
  6458. return matrix;
  6459. };
  6460. /**
  6461. * Computes a reflection matrix from a plane
  6462. * @param plane defines the reflection plane
  6463. * @param result defines the target matrix
  6464. */
  6465. Matrix.ReflectionToRef = function (plane, result) {
  6466. plane.normalize();
  6467. var x = plane.normal.x;
  6468. var y = plane.normal.y;
  6469. var z = plane.normal.z;
  6470. var temp = -2 * x;
  6471. var temp2 = -2 * y;
  6472. var temp3 = -2 * z;
  6473. result.m[0] = (temp * x) + 1;
  6474. result.m[1] = temp2 * x;
  6475. result.m[2] = temp3 * x;
  6476. result.m[3] = 0.0;
  6477. result.m[4] = temp * y;
  6478. result.m[5] = (temp2 * y) + 1;
  6479. result.m[6] = temp3 * y;
  6480. result.m[7] = 0.0;
  6481. result.m[8] = temp * z;
  6482. result.m[9] = temp2 * z;
  6483. result.m[10] = (temp3 * z) + 1;
  6484. result.m[11] = 0.0;
  6485. result.m[12] = temp * plane.d;
  6486. result.m[13] = temp2 * plane.d;
  6487. result.m[14] = temp3 * plane.d;
  6488. result.m[15] = 1.0;
  6489. result._markAsUpdated();
  6490. };
  6491. /**
  6492. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6493. * @param xaxis defines the value of the 1st axis
  6494. * @param yaxis defines the value of the 2nd axis
  6495. * @param zaxis defines the value of the 3rd axis
  6496. * @param result defines the target matrix
  6497. */
  6498. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6499. result.m[0] = xaxis.x;
  6500. result.m[1] = xaxis.y;
  6501. result.m[2] = xaxis.z;
  6502. result.m[3] = 0.0;
  6503. result.m[4] = yaxis.x;
  6504. result.m[5] = yaxis.y;
  6505. result.m[6] = yaxis.z;
  6506. result.m[7] = 0.0;
  6507. result.m[8] = zaxis.x;
  6508. result.m[9] = zaxis.y;
  6509. result.m[10] = zaxis.z;
  6510. result.m[11] = 0.0;
  6511. result.m[12] = 0.0;
  6512. result.m[13] = 0.0;
  6513. result.m[14] = 0.0;
  6514. result.m[15] = 1.0;
  6515. result._markAsUpdated();
  6516. };
  6517. /**
  6518. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6519. * @param quat defines the quaternion to use
  6520. * @param result defines the target matrix
  6521. */
  6522. Matrix.FromQuaternionToRef = function (quat, result) {
  6523. var xx = quat.x * quat.x;
  6524. var yy = quat.y * quat.y;
  6525. var zz = quat.z * quat.z;
  6526. var xy = quat.x * quat.y;
  6527. var zw = quat.z * quat.w;
  6528. var zx = quat.z * quat.x;
  6529. var yw = quat.y * quat.w;
  6530. var yz = quat.y * quat.z;
  6531. var xw = quat.x * quat.w;
  6532. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6533. result.m[1] = 2.0 * (xy + zw);
  6534. result.m[2] = 2.0 * (zx - yw);
  6535. result.m[3] = 0.0;
  6536. result.m[4] = 2.0 * (xy - zw);
  6537. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6538. result.m[6] = 2.0 * (yz + xw);
  6539. result.m[7] = 0.0;
  6540. result.m[8] = 2.0 * (zx + yw);
  6541. result.m[9] = 2.0 * (yz - xw);
  6542. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6543. result.m[11] = 0.0;
  6544. result.m[12] = 0.0;
  6545. result.m[13] = 0.0;
  6546. result.m[14] = 0.0;
  6547. result.m[15] = 1.0;
  6548. result._markAsUpdated();
  6549. };
  6550. Matrix._tempQuaternion = new Quaternion();
  6551. Matrix._xAxis = Vector3.Zero();
  6552. Matrix._yAxis = Vector3.Zero();
  6553. Matrix._zAxis = Vector3.Zero();
  6554. Matrix._updateFlagSeed = 0;
  6555. Matrix._identityReadOnly = Matrix.Identity();
  6556. return Matrix;
  6557. }());
  6558. BABYLON.Matrix = Matrix;
  6559. var Plane = /** @class */ (function () {
  6560. /**
  6561. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6562. */
  6563. function Plane(a, b, c, d) {
  6564. this.normal = new Vector3(a, b, c);
  6565. this.d = d;
  6566. }
  6567. /**
  6568. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6569. */
  6570. Plane.prototype.asArray = function () {
  6571. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6572. };
  6573. // Methods
  6574. /**
  6575. * Returns a new plane copied from the current Plane.
  6576. */
  6577. Plane.prototype.clone = function () {
  6578. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6579. };
  6580. /**
  6581. * Returns the string "Plane".
  6582. */
  6583. Plane.prototype.getClassName = function () {
  6584. return "Plane";
  6585. };
  6586. /**
  6587. * Returns the Plane hash code.
  6588. */
  6589. Plane.prototype.getHashCode = function () {
  6590. var hash = this.normal.getHashCode();
  6591. hash = (hash * 397) ^ (this.d || 0);
  6592. return hash;
  6593. };
  6594. /**
  6595. * Normalize the current Plane in place.
  6596. * Returns the updated Plane.
  6597. */
  6598. Plane.prototype.normalize = function () {
  6599. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6600. var magnitude = 0.0;
  6601. if (norm !== 0) {
  6602. magnitude = 1.0 / norm;
  6603. }
  6604. this.normal.x *= magnitude;
  6605. this.normal.y *= magnitude;
  6606. this.normal.z *= magnitude;
  6607. this.d *= magnitude;
  6608. return this;
  6609. };
  6610. /**
  6611. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6612. */
  6613. Plane.prototype.transform = function (transformation) {
  6614. var transposedMatrix = Matrix.Transpose(transformation);
  6615. var x = this.normal.x;
  6616. var y = this.normal.y;
  6617. var z = this.normal.z;
  6618. var d = this.d;
  6619. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6620. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6621. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6622. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6623. return new Plane(normalX, normalY, normalZ, finalD);
  6624. };
  6625. /**
  6626. * Returns the dot product (float) of the point coordinates and the plane normal.
  6627. */
  6628. Plane.prototype.dotCoordinate = function (point) {
  6629. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6630. };
  6631. /**
  6632. * Updates the current Plane from the plane defined by the three given points.
  6633. * Returns the updated Plane.
  6634. */
  6635. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6636. var x1 = point2.x - point1.x;
  6637. var y1 = point2.y - point1.y;
  6638. var z1 = point2.z - point1.z;
  6639. var x2 = point3.x - point1.x;
  6640. var y2 = point3.y - point1.y;
  6641. var z2 = point3.z - point1.z;
  6642. var yz = (y1 * z2) - (z1 * y2);
  6643. var xz = (z1 * x2) - (x1 * z2);
  6644. var xy = (x1 * y2) - (y1 * x2);
  6645. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6646. var invPyth;
  6647. if (pyth !== 0) {
  6648. invPyth = 1.0 / pyth;
  6649. }
  6650. else {
  6651. invPyth = 0.0;
  6652. }
  6653. this.normal.x = yz * invPyth;
  6654. this.normal.y = xz * invPyth;
  6655. this.normal.z = xy * invPyth;
  6656. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6657. return this;
  6658. };
  6659. /**
  6660. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6661. */
  6662. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6663. var dot = Vector3.Dot(this.normal, direction);
  6664. return (dot <= epsilon);
  6665. };
  6666. /**
  6667. * Returns the signed distance (float) from the given point to the Plane.
  6668. */
  6669. Plane.prototype.signedDistanceTo = function (point) {
  6670. return Vector3.Dot(point, this.normal) + this.d;
  6671. };
  6672. // Statics
  6673. /**
  6674. * Returns a new Plane from the given array.
  6675. */
  6676. Plane.FromArray = function (array) {
  6677. return new Plane(array[0], array[1], array[2], array[3]);
  6678. };
  6679. /**
  6680. * Returns a new Plane defined by the three given points.
  6681. */
  6682. Plane.FromPoints = function (point1, point2, point3) {
  6683. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6684. result.copyFromPoints(point1, point2, point3);
  6685. return result;
  6686. };
  6687. /**
  6688. * Returns a new Plane the normal vector to this plane at the given origin point.
  6689. * Note : the vector "normal" is updated because normalized.
  6690. */
  6691. Plane.FromPositionAndNormal = function (origin, normal) {
  6692. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6693. normal.normalize();
  6694. result.normal = normal;
  6695. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6696. return result;
  6697. };
  6698. /**
  6699. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6700. */
  6701. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6702. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6703. return Vector3.Dot(point, normal) + d;
  6704. };
  6705. return Plane;
  6706. }());
  6707. BABYLON.Plane = Plane;
  6708. var Viewport = /** @class */ (function () {
  6709. /**
  6710. * Creates a Viewport object located at (x, y) and sized (width, height).
  6711. */
  6712. function Viewport(x, y, width, height) {
  6713. this.x = x;
  6714. this.y = y;
  6715. this.width = width;
  6716. this.height = height;
  6717. }
  6718. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6719. if (renderWidthOrEngine.getRenderWidth) {
  6720. var engine = renderWidthOrEngine;
  6721. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6722. }
  6723. var renderWidth = renderWidthOrEngine;
  6724. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6725. };
  6726. /**
  6727. * Returns a new Viewport copied from the current one.
  6728. */
  6729. Viewport.prototype.clone = function () {
  6730. return new Viewport(this.x, this.y, this.width, this.height);
  6731. };
  6732. return Viewport;
  6733. }());
  6734. BABYLON.Viewport = Viewport;
  6735. var Frustum = /** @class */ (function () {
  6736. function Frustum() {
  6737. }
  6738. /**
  6739. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6740. */
  6741. Frustum.GetPlanes = function (transform) {
  6742. var frustumPlanes = [];
  6743. for (var index = 0; index < 6; index++) {
  6744. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6745. }
  6746. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6747. return frustumPlanes;
  6748. };
  6749. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6750. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6751. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6752. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6753. frustumPlane.d = transform.m[15] + transform.m[14];
  6754. frustumPlane.normalize();
  6755. };
  6756. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6757. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6758. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6759. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6760. frustumPlane.d = transform.m[15] - transform.m[14];
  6761. frustumPlane.normalize();
  6762. };
  6763. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6764. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6765. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6766. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6767. frustumPlane.d = transform.m[15] + transform.m[12];
  6768. frustumPlane.normalize();
  6769. };
  6770. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6771. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6772. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6773. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6774. frustumPlane.d = transform.m[15] - transform.m[12];
  6775. frustumPlane.normalize();
  6776. };
  6777. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6778. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6779. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6780. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6781. frustumPlane.d = transform.m[15] - transform.m[13];
  6782. frustumPlane.normalize();
  6783. };
  6784. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6785. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6786. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6787. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6788. frustumPlane.d = transform.m[15] + transform.m[13];
  6789. frustumPlane.normalize();
  6790. };
  6791. /**
  6792. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6793. */
  6794. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6795. // Near
  6796. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6797. // Far
  6798. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6799. // Left
  6800. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6801. // Right
  6802. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6803. // Top
  6804. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6805. // Bottom
  6806. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6807. };
  6808. return Frustum;
  6809. }());
  6810. BABYLON.Frustum = Frustum;
  6811. /** Defines supported spaces */
  6812. var Space;
  6813. (function (Space) {
  6814. /** Local (object) space */
  6815. Space[Space["LOCAL"] = 0] = "LOCAL";
  6816. /** World space */
  6817. Space[Space["WORLD"] = 1] = "WORLD";
  6818. /** Bone space */
  6819. Space[Space["BONE"] = 2] = "BONE";
  6820. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6821. /** Defines the 3 main axes */
  6822. var Axis = /** @class */ (function () {
  6823. function Axis() {
  6824. }
  6825. /** X axis */
  6826. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6827. /** Y axis */
  6828. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6829. /** Z axis */
  6830. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6831. return Axis;
  6832. }());
  6833. BABYLON.Axis = Axis;
  6834. ;
  6835. var BezierCurve = /** @class */ (function () {
  6836. function BezierCurve() {
  6837. }
  6838. /**
  6839. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6840. */
  6841. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6842. // Extract X (which is equal to time here)
  6843. var f0 = 1 - 3 * x2 + 3 * x1;
  6844. var f1 = 3 * x2 - 6 * x1;
  6845. var f2 = 3 * x1;
  6846. var refinedT = t;
  6847. for (var i = 0; i < 5; i++) {
  6848. var refinedT2 = refinedT * refinedT;
  6849. var refinedT3 = refinedT2 * refinedT;
  6850. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6851. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6852. refinedT -= (x - t) * slope;
  6853. refinedT = Math.min(1, Math.max(0, refinedT));
  6854. }
  6855. // Resolve cubic bezier for the given x
  6856. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6857. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6858. Math.pow(refinedT, 3);
  6859. };
  6860. return BezierCurve;
  6861. }());
  6862. BABYLON.BezierCurve = BezierCurve;
  6863. /**
  6864. * Defines potential orientation for back face culling
  6865. */
  6866. var Orientation;
  6867. (function (Orientation) {
  6868. /**
  6869. * Clockwise
  6870. */
  6871. Orientation[Orientation["CW"] = 0] = "CW";
  6872. /** Counter clockwise */
  6873. Orientation[Orientation["CCW"] = 1] = "CCW";
  6874. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6875. /**
  6876. * Defines angle representation
  6877. */
  6878. var Angle = /** @class */ (function () {
  6879. /**
  6880. * Creates an Angle object of "radians" radians (float).
  6881. */
  6882. function Angle(radians) {
  6883. this._radians = radians;
  6884. if (this._radians < 0.0)
  6885. this._radians += (2.0 * Math.PI);
  6886. }
  6887. /**
  6888. * Get value in degrees
  6889. * @returns the Angle value in degrees (float)
  6890. */
  6891. Angle.prototype.degrees = function () {
  6892. return this._radians * 180.0 / Math.PI;
  6893. };
  6894. /**
  6895. * Get value in radians
  6896. * @returns the Angle value in radians (float)
  6897. */
  6898. Angle.prototype.radians = function () {
  6899. return this._radians;
  6900. };
  6901. /**
  6902. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6903. * @param a defines first vector
  6904. * @param b defines second vector
  6905. * @returns a new Angle
  6906. */
  6907. Angle.BetweenTwoPoints = function (a, b) {
  6908. var delta = b.subtract(a);
  6909. var theta = Math.atan2(delta.y, delta.x);
  6910. return new Angle(theta);
  6911. };
  6912. /**
  6913. * Gets a new Angle object from the given float in radians
  6914. * @param radians defines the angle value in radians
  6915. * @returns a new Angle
  6916. */
  6917. Angle.FromRadians = function (radians) {
  6918. return new Angle(radians);
  6919. };
  6920. /**
  6921. * Gets a new Angle object from the given float in degrees
  6922. * @param degrees defines the angle value in degrees
  6923. * @returns a new Angle
  6924. */
  6925. Angle.FromDegrees = function (degrees) {
  6926. return new Angle(degrees * Math.PI / 180.0);
  6927. };
  6928. return Angle;
  6929. }());
  6930. BABYLON.Angle = Angle;
  6931. var Arc2 = /** @class */ (function () {
  6932. /**
  6933. * Creates an Arc object from the three given points : start, middle and end.
  6934. */
  6935. function Arc2(startPoint, midPoint, endPoint) {
  6936. this.startPoint = startPoint;
  6937. this.midPoint = midPoint;
  6938. this.endPoint = endPoint;
  6939. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6940. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6941. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6942. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6943. 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);
  6944. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6945. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6946. var a1 = this.startAngle.degrees();
  6947. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6948. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6949. // angles correction
  6950. if (a2 - a1 > +180.0)
  6951. a2 -= 360.0;
  6952. if (a2 - a1 < -180.0)
  6953. a2 += 360.0;
  6954. if (a3 - a2 > +180.0)
  6955. a3 -= 360.0;
  6956. if (a3 - a2 < -180.0)
  6957. a3 += 360.0;
  6958. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6959. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6960. }
  6961. return Arc2;
  6962. }());
  6963. BABYLON.Arc2 = Arc2;
  6964. var Path2 = /** @class */ (function () {
  6965. /**
  6966. * Creates a Path2 object from the starting 2D coordinates x and y.
  6967. */
  6968. function Path2(x, y) {
  6969. this._points = new Array();
  6970. this._length = 0.0;
  6971. this.closed = false;
  6972. this._points.push(new Vector2(x, y));
  6973. }
  6974. /**
  6975. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6976. * Returns the updated Path2.
  6977. */
  6978. Path2.prototype.addLineTo = function (x, y) {
  6979. if (this.closed) {
  6980. return this;
  6981. }
  6982. var newPoint = new Vector2(x, y);
  6983. var previousPoint = this._points[this._points.length - 1];
  6984. this._points.push(newPoint);
  6985. this._length += newPoint.subtract(previousPoint).length();
  6986. return this;
  6987. };
  6988. /**
  6989. * 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.
  6990. * Returns the updated Path2.
  6991. */
  6992. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6993. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6994. if (this.closed) {
  6995. return this;
  6996. }
  6997. var startPoint = this._points[this._points.length - 1];
  6998. var midPoint = new Vector2(midX, midY);
  6999. var endPoint = new Vector2(endX, endY);
  7000. var arc = new Arc2(startPoint, midPoint, endPoint);
  7001. var increment = arc.angle.radians() / numberOfSegments;
  7002. if (arc.orientation === Orientation.CW)
  7003. increment *= -1;
  7004. var currentAngle = arc.startAngle.radians() + increment;
  7005. for (var i = 0; i < numberOfSegments; i++) {
  7006. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7007. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7008. this.addLineTo(x, y);
  7009. currentAngle += increment;
  7010. }
  7011. return this;
  7012. };
  7013. /**
  7014. * Closes the Path2.
  7015. * Returns the Path2.
  7016. */
  7017. Path2.prototype.close = function () {
  7018. this.closed = true;
  7019. return this;
  7020. };
  7021. /**
  7022. * Returns the Path2 total length (float).
  7023. */
  7024. Path2.prototype.length = function () {
  7025. var result = this._length;
  7026. if (!this.closed) {
  7027. var lastPoint = this._points[this._points.length - 1];
  7028. var firstPoint = this._points[0];
  7029. result += (firstPoint.subtract(lastPoint).length());
  7030. }
  7031. return result;
  7032. };
  7033. /**
  7034. * Returns the Path2 internal array of points.
  7035. */
  7036. Path2.prototype.getPoints = function () {
  7037. return this._points;
  7038. };
  7039. /**
  7040. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7041. */
  7042. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7043. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7044. return Vector2.Zero();
  7045. }
  7046. var lengthPosition = normalizedLengthPosition * this.length();
  7047. var previousOffset = 0;
  7048. for (var i = 0; i < this._points.length; i++) {
  7049. var j = (i + 1) % this._points.length;
  7050. var a = this._points[i];
  7051. var b = this._points[j];
  7052. var bToA = b.subtract(a);
  7053. var nextOffset = (bToA.length() + previousOffset);
  7054. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7055. var dir = bToA.normalize();
  7056. var localOffset = lengthPosition - previousOffset;
  7057. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7058. }
  7059. previousOffset = nextOffset;
  7060. }
  7061. return Vector2.Zero();
  7062. };
  7063. /**
  7064. * Returns a new Path2 starting at the coordinates (x, y).
  7065. */
  7066. Path2.StartingAt = function (x, y) {
  7067. return new Path2(x, y);
  7068. };
  7069. return Path2;
  7070. }());
  7071. BABYLON.Path2 = Path2;
  7072. var Path3D = /** @class */ (function () {
  7073. /**
  7074. * new Path3D(path, normal, raw)
  7075. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7076. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7077. * path : an array of Vector3, the curve axis of the Path3D
  7078. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7079. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7080. */
  7081. function Path3D(path, firstNormal, raw) {
  7082. if (firstNormal === void 0) { firstNormal = null; }
  7083. this.path = path;
  7084. this._curve = new Array();
  7085. this._distances = new Array();
  7086. this._tangents = new Array();
  7087. this._normals = new Array();
  7088. this._binormals = new Array();
  7089. for (var p = 0; p < path.length; p++) {
  7090. this._curve[p] = path[p].clone(); // hard copy
  7091. }
  7092. this._raw = raw || false;
  7093. this._compute(firstNormal);
  7094. }
  7095. /**
  7096. * Returns the Path3D array of successive Vector3 designing its curve.
  7097. */
  7098. Path3D.prototype.getCurve = function () {
  7099. return this._curve;
  7100. };
  7101. /**
  7102. * Returns an array populated with tangent vectors on each Path3D curve point.
  7103. */
  7104. Path3D.prototype.getTangents = function () {
  7105. return this._tangents;
  7106. };
  7107. /**
  7108. * Returns an array populated with normal vectors on each Path3D curve point.
  7109. */
  7110. Path3D.prototype.getNormals = function () {
  7111. return this._normals;
  7112. };
  7113. /**
  7114. * Returns an array populated with binormal vectors on each Path3D curve point.
  7115. */
  7116. Path3D.prototype.getBinormals = function () {
  7117. return this._binormals;
  7118. };
  7119. /**
  7120. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7121. */
  7122. Path3D.prototype.getDistances = function () {
  7123. return this._distances;
  7124. };
  7125. /**
  7126. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7127. * Returns the same object updated.
  7128. */
  7129. Path3D.prototype.update = function (path, firstNormal) {
  7130. if (firstNormal === void 0) { firstNormal = null; }
  7131. for (var p = 0; p < path.length; p++) {
  7132. this._curve[p].x = path[p].x;
  7133. this._curve[p].y = path[p].y;
  7134. this._curve[p].z = path[p].z;
  7135. }
  7136. this._compute(firstNormal);
  7137. return this;
  7138. };
  7139. // private function compute() : computes tangents, normals and binormals
  7140. Path3D.prototype._compute = function (firstNormal) {
  7141. var l = this._curve.length;
  7142. // first and last tangents
  7143. this._tangents[0] = this._getFirstNonNullVector(0);
  7144. if (!this._raw) {
  7145. this._tangents[0].normalize();
  7146. }
  7147. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7148. if (!this._raw) {
  7149. this._tangents[l - 1].normalize();
  7150. }
  7151. // normals and binormals at first point : arbitrary vector with _normalVector()
  7152. var tg0 = this._tangents[0];
  7153. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7154. this._normals[0] = pp0;
  7155. if (!this._raw) {
  7156. this._normals[0].normalize();
  7157. }
  7158. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7159. if (!this._raw) {
  7160. this._binormals[0].normalize();
  7161. }
  7162. this._distances[0] = 0.0;
  7163. // normals and binormals : next points
  7164. var prev; // previous vector (segment)
  7165. var cur; // current vector (segment)
  7166. var curTang; // current tangent
  7167. // previous normal
  7168. var prevBinor; // previous binormal
  7169. for (var i = 1; i < l; i++) {
  7170. // tangents
  7171. prev = this._getLastNonNullVector(i);
  7172. if (i < l - 1) {
  7173. cur = this._getFirstNonNullVector(i);
  7174. this._tangents[i] = prev.add(cur);
  7175. this._tangents[i].normalize();
  7176. }
  7177. this._distances[i] = this._distances[i - 1] + prev.length();
  7178. // normals and binormals
  7179. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7180. curTang = this._tangents[i];
  7181. prevBinor = this._binormals[i - 1];
  7182. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7183. if (!this._raw) {
  7184. this._normals[i].normalize();
  7185. }
  7186. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7187. if (!this._raw) {
  7188. this._binormals[i].normalize();
  7189. }
  7190. }
  7191. };
  7192. // private function getFirstNonNullVector(index)
  7193. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7194. Path3D.prototype._getFirstNonNullVector = function (index) {
  7195. var i = 1;
  7196. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7197. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7198. i++;
  7199. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7200. }
  7201. return nNVector;
  7202. };
  7203. // private function getLastNonNullVector(index)
  7204. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7205. Path3D.prototype._getLastNonNullVector = function (index) {
  7206. var i = 1;
  7207. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7208. while (nLVector.length() === 0 && index > i + 1) {
  7209. i++;
  7210. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7211. }
  7212. return nLVector;
  7213. };
  7214. // private function normalVector(v0, vt, va) :
  7215. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7216. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7217. Path3D.prototype._normalVector = function (v0, vt, va) {
  7218. var normal0;
  7219. var tgl = vt.length();
  7220. if (tgl === 0.0) {
  7221. tgl = 1.0;
  7222. }
  7223. if (va === undefined || va === null) {
  7224. var point;
  7225. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7226. point = new Vector3(0.0, -1.0, 0.0);
  7227. }
  7228. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7229. point = new Vector3(1.0, 0.0, 0.0);
  7230. }
  7231. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7232. point = new Vector3(0.0, 0.0, 1.0);
  7233. }
  7234. else {
  7235. point = Vector3.Zero();
  7236. }
  7237. normal0 = Vector3.Cross(vt, point);
  7238. }
  7239. else {
  7240. normal0 = Vector3.Cross(vt, va);
  7241. Vector3.CrossToRef(normal0, vt, normal0);
  7242. }
  7243. normal0.normalize();
  7244. return normal0;
  7245. };
  7246. return Path3D;
  7247. }());
  7248. BABYLON.Path3D = Path3D;
  7249. var Curve3 = /** @class */ (function () {
  7250. /**
  7251. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7252. * A Curve3 is designed from a series of successive Vector3.
  7253. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7254. */
  7255. function Curve3(points) {
  7256. this._length = 0.0;
  7257. this._points = points;
  7258. this._length = this._computeLength(points);
  7259. }
  7260. /**
  7261. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7262. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7263. * @param v1 (Vector3) the control point
  7264. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7265. * @param nbPoints (integer) the wanted number of points in the curve
  7266. */
  7267. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7268. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7269. var bez = new Array();
  7270. var equation = function (t, val0, val1, val2) {
  7271. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7272. return res;
  7273. };
  7274. for (var i = 0; i <= nbPoints; i++) {
  7275. 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)));
  7276. }
  7277. return new Curve3(bez);
  7278. };
  7279. /**
  7280. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7281. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7282. * @param v1 (Vector3) the first control point
  7283. * @param v2 (Vector3) the second control point
  7284. * @param v3 (Vector3) the end point of the Cubic Bezier
  7285. * @param nbPoints (integer) the wanted number of points in the curve
  7286. */
  7287. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7288. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7289. var bez = new Array();
  7290. var equation = function (t, val0, val1, val2, val3) {
  7291. 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;
  7292. return res;
  7293. };
  7294. for (var i = 0; i <= nbPoints; i++) {
  7295. 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)));
  7296. }
  7297. return new Curve3(bez);
  7298. };
  7299. /**
  7300. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7301. * @param p1 (Vector3) the origin point of the Hermite Spline
  7302. * @param t1 (Vector3) the tangent vector at the origin point
  7303. * @param p2 (Vector3) the end point of the Hermite Spline
  7304. * @param t2 (Vector3) the tangent vector at the end point
  7305. * @param nbPoints (integer) the wanted number of points in the curve
  7306. */
  7307. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7308. var hermite = new Array();
  7309. var step = 1.0 / nbPoints;
  7310. for (var i = 0; i <= nbPoints; i++) {
  7311. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7312. }
  7313. return new Curve3(hermite);
  7314. };
  7315. /**
  7316. * Returns a Curve3 object along a CatmullRom Spline curve :
  7317. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7318. * @param nbPoints (integer) the wanted number of points between each curve control points
  7319. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7320. */
  7321. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7322. var catmullRom = new Array();
  7323. var step = 1.0 / nbPoints;
  7324. var amount = 0.0;
  7325. if (closed) {
  7326. var pointsCount = points.length;
  7327. for (var i = 0; i < pointsCount; i++) {
  7328. amount = 0;
  7329. for (var c = 0; c < nbPoints; c++) {
  7330. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7331. amount += step;
  7332. }
  7333. }
  7334. catmullRom.push(catmullRom[0]);
  7335. }
  7336. else {
  7337. var totalPoints = new Array();
  7338. totalPoints.push(points[0].clone());
  7339. Array.prototype.push.apply(totalPoints, points);
  7340. totalPoints.push(points[points.length - 1].clone());
  7341. for (var i = 0; i < totalPoints.length - 3; i++) {
  7342. amount = 0;
  7343. for (var c = 0; c < nbPoints; c++) {
  7344. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7345. amount += step;
  7346. }
  7347. }
  7348. i--;
  7349. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7350. }
  7351. return new Curve3(catmullRom);
  7352. };
  7353. /**
  7354. * Returns the Curve3 stored array of successive Vector3
  7355. */
  7356. Curve3.prototype.getPoints = function () {
  7357. return this._points;
  7358. };
  7359. /**
  7360. * Returns the computed length (float) of the curve.
  7361. */
  7362. Curve3.prototype.length = function () {
  7363. return this._length;
  7364. };
  7365. /**
  7366. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7367. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7368. * curveA and curveB keep unchanged.
  7369. */
  7370. Curve3.prototype.continue = function (curve) {
  7371. var lastPoint = this._points[this._points.length - 1];
  7372. var continuedPoints = this._points.slice();
  7373. var curvePoints = curve.getPoints();
  7374. for (var i = 1; i < curvePoints.length; i++) {
  7375. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7376. }
  7377. var continuedCurve = new Curve3(continuedPoints);
  7378. return continuedCurve;
  7379. };
  7380. Curve3.prototype._computeLength = function (path) {
  7381. var l = 0;
  7382. for (var i = 1; i < path.length; i++) {
  7383. l += (path[i].subtract(path[i - 1])).length();
  7384. }
  7385. return l;
  7386. };
  7387. return Curve3;
  7388. }());
  7389. BABYLON.Curve3 = Curve3;
  7390. // Vertex formats
  7391. var PositionNormalVertex = /** @class */ (function () {
  7392. function PositionNormalVertex(position, normal) {
  7393. if (position === void 0) { position = Vector3.Zero(); }
  7394. if (normal === void 0) { normal = Vector3.Up(); }
  7395. this.position = position;
  7396. this.normal = normal;
  7397. }
  7398. PositionNormalVertex.prototype.clone = function () {
  7399. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7400. };
  7401. return PositionNormalVertex;
  7402. }());
  7403. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7404. var PositionNormalTextureVertex = /** @class */ (function () {
  7405. function PositionNormalTextureVertex(position, normal, uv) {
  7406. if (position === void 0) { position = Vector3.Zero(); }
  7407. if (normal === void 0) { normal = Vector3.Up(); }
  7408. if (uv === void 0) { uv = Vector2.Zero(); }
  7409. this.position = position;
  7410. this.normal = normal;
  7411. this.uv = uv;
  7412. }
  7413. PositionNormalTextureVertex.prototype.clone = function () {
  7414. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7415. };
  7416. return PositionNormalTextureVertex;
  7417. }());
  7418. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7419. // Temporary pre-allocated objects for engine internal use
  7420. // usage in any internal function :
  7421. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7422. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7423. var Tmp = /** @class */ (function () {
  7424. function Tmp() {
  7425. }
  7426. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7427. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7428. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7429. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7430. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7431. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7432. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7433. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7434. Matrix.Zero(), Matrix.Zero(),
  7435. Matrix.Zero(), Matrix.Zero(),
  7436. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7437. return Tmp;
  7438. }());
  7439. BABYLON.Tmp = Tmp;
  7440. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7441. var MathTmp = /** @class */ (function () {
  7442. function MathTmp() {
  7443. }
  7444. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7445. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7446. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7447. return MathTmp;
  7448. }());
  7449. })(BABYLON || (BABYLON = {}));
  7450. //# sourceMappingURL=babylon.math.js.map
  7451. var BABYLON;
  7452. (function (BABYLON) {
  7453. var Scalar = /** @class */ (function () {
  7454. function Scalar() {
  7455. }
  7456. /**
  7457. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7458. */
  7459. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7460. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7461. var num = a - b;
  7462. return -epsilon <= num && num <= epsilon;
  7463. };
  7464. /**
  7465. * Returns a string : the upper case translation of the number i to hexadecimal.
  7466. */
  7467. Scalar.ToHex = function (i) {
  7468. var str = i.toString(16);
  7469. if (i <= 15) {
  7470. return ("0" + str).toUpperCase();
  7471. }
  7472. return str.toUpperCase();
  7473. };
  7474. /**
  7475. * Returns -1 if value is negative and +1 is value is positive.
  7476. * Returns the value itself if it's equal to zero.
  7477. */
  7478. Scalar.Sign = function (value) {
  7479. value = +value; // convert to a number
  7480. if (value === 0 || isNaN(value))
  7481. return value;
  7482. return value > 0 ? 1 : -1;
  7483. };
  7484. /**
  7485. * Returns the value itself if it's between min and max.
  7486. * Returns min if the value is lower than min.
  7487. * Returns max if the value is greater than max.
  7488. */
  7489. Scalar.Clamp = function (value, min, max) {
  7490. if (min === void 0) { min = 0; }
  7491. if (max === void 0) { max = 1; }
  7492. return Math.min(max, Math.max(min, value));
  7493. };
  7494. /**
  7495. * Returns the log2 of value.
  7496. */
  7497. Scalar.Log2 = function (value) {
  7498. return Math.log(value) * Math.LOG2E;
  7499. };
  7500. /**
  7501. * Loops the value, so that it is never larger than length and never smaller than 0.
  7502. *
  7503. * This is similar to the modulo operator but it works with floating point numbers.
  7504. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7505. * With t = 5 and length = 2.5, the result would be 0.0.
  7506. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7507. */
  7508. Scalar.Repeat = function (value, length) {
  7509. return value - Math.floor(value / length) * length;
  7510. };
  7511. /**
  7512. * Normalize the value between 0.0 and 1.0 using min and max values
  7513. */
  7514. Scalar.Normalize = function (value, min, max) {
  7515. return (value - min) / (max - min);
  7516. };
  7517. /**
  7518. * Denormalize the value from 0.0 and 1.0 using min and max values
  7519. */
  7520. Scalar.Denormalize = function (normalized, min, max) {
  7521. return (normalized * (max - min) + min);
  7522. };
  7523. /**
  7524. * Calculates the shortest difference between two given angles given in degrees.
  7525. */
  7526. Scalar.DeltaAngle = function (current, target) {
  7527. var num = Scalar.Repeat(target - current, 360.0);
  7528. if (num > 180.0) {
  7529. num -= 360.0;
  7530. }
  7531. return num;
  7532. };
  7533. /**
  7534. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7535. *
  7536. * The returned value will move back and forth between 0 and length
  7537. */
  7538. Scalar.PingPong = function (tx, length) {
  7539. var t = Scalar.Repeat(tx, length * 2.0);
  7540. return length - Math.abs(t - length);
  7541. };
  7542. /**
  7543. * Interpolates between min and max with smoothing at the limits.
  7544. *
  7545. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7546. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7547. */
  7548. Scalar.SmoothStep = function (from, to, tx) {
  7549. var t = Scalar.Clamp(tx);
  7550. t = -2.0 * t * t * t + 3.0 * t * t;
  7551. return to * t + from * (1.0 - t);
  7552. };
  7553. /**
  7554. * Moves a value current towards target.
  7555. *
  7556. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7557. * Negative values of maxDelta pushes the value away from target.
  7558. */
  7559. Scalar.MoveTowards = function (current, target, maxDelta) {
  7560. var result = 0;
  7561. if (Math.abs(target - current) <= maxDelta) {
  7562. result = target;
  7563. }
  7564. else {
  7565. result = current + Scalar.Sign(target - current) * maxDelta;
  7566. }
  7567. return result;
  7568. };
  7569. /**
  7570. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7571. *
  7572. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7573. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7574. */
  7575. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7576. var num = Scalar.DeltaAngle(current, target);
  7577. var result = 0;
  7578. if (-maxDelta < num && num < maxDelta) {
  7579. result = target;
  7580. }
  7581. else {
  7582. target = current + num;
  7583. result = Scalar.MoveTowards(current, target, maxDelta);
  7584. }
  7585. return result;
  7586. };
  7587. /**
  7588. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7589. */
  7590. Scalar.Lerp = function (start, end, amount) {
  7591. return start + ((end - start) * amount);
  7592. };
  7593. /**
  7594. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7595. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7596. */
  7597. Scalar.LerpAngle = function (start, end, amount) {
  7598. var num = Scalar.Repeat(end - start, 360.0);
  7599. if (num > 180.0) {
  7600. num -= 360.0;
  7601. }
  7602. return start + num * Scalar.Clamp(amount);
  7603. };
  7604. /**
  7605. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7606. */
  7607. Scalar.InverseLerp = function (a, b, value) {
  7608. var result = 0;
  7609. if (a != b) {
  7610. result = Scalar.Clamp((value - a) / (b - a));
  7611. }
  7612. else {
  7613. result = 0.0;
  7614. }
  7615. return result;
  7616. };
  7617. /**
  7618. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7619. */
  7620. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7621. var squared = amount * amount;
  7622. var cubed = amount * squared;
  7623. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7624. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7625. var part3 = (cubed - (2.0 * squared)) + amount;
  7626. var part4 = cubed - squared;
  7627. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7628. };
  7629. /**
  7630. * Returns a random float number between and min and max values
  7631. */
  7632. Scalar.RandomRange = function (min, max) {
  7633. if (min === max)
  7634. return min;
  7635. return ((Math.random() * (max - min)) + min);
  7636. };
  7637. /**
  7638. * This function returns percentage of a number in a given range.
  7639. *
  7640. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7641. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7642. */
  7643. Scalar.RangeToPercent = function (number, min, max) {
  7644. return ((number - min) / (max - min));
  7645. };
  7646. /**
  7647. * This function returns number that corresponds to the percentage in a given range.
  7648. *
  7649. * PercentToRange(0.34,0,100) will return 34.
  7650. */
  7651. Scalar.PercentToRange = function (percent, min, max) {
  7652. return ((max - min) * percent + min);
  7653. };
  7654. /**
  7655. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7656. * @param angle The angle to normalize in radian.
  7657. * @return The converted angle.
  7658. */
  7659. Scalar.NormalizeRadians = function (angle) {
  7660. // More precise but slower version kept for reference.
  7661. // angle = angle % Tools.TwoPi;
  7662. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7663. //if (angle > Math.PI) {
  7664. // angle -= Tools.TwoPi;
  7665. //}
  7666. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7667. return angle;
  7668. };
  7669. /**
  7670. * Two pi constants convenient for computation.
  7671. */
  7672. Scalar.TwoPi = Math.PI * 2;
  7673. return Scalar;
  7674. }());
  7675. BABYLON.Scalar = Scalar;
  7676. })(BABYLON || (BABYLON = {}));
  7677. //# sourceMappingURL=babylon.math.scalar.js.map
  7678. //# sourceMappingURL=babylon.mixins.js.map
  7679. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7680. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7681. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7682. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7683. //# sourceMappingURL=babylon.webgl2.js.map
  7684. var BABYLON;
  7685. (function (BABYLON) {
  7686. var __decoratorInitialStore = {};
  7687. var __mergedStore = {};
  7688. var _copySource = function (creationFunction, source, instanciate) {
  7689. var destination = creationFunction();
  7690. // Tags
  7691. if (BABYLON.Tags) {
  7692. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7693. }
  7694. var classStore = getMergedStore(destination);
  7695. // Properties
  7696. for (var property in classStore) {
  7697. var propertyDescriptor = classStore[property];
  7698. var sourceProperty = source[property];
  7699. var propertyType = propertyDescriptor.type;
  7700. if (sourceProperty !== undefined && sourceProperty !== null) {
  7701. switch (propertyType) {
  7702. case 0: // Value
  7703. case 6: // Mesh reference
  7704. case 11: // Camera reference
  7705. destination[property] = sourceProperty;
  7706. break;
  7707. case 1: // Texture
  7708. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7709. break;
  7710. case 2: // Color3
  7711. case 3: // FresnelParameters
  7712. case 4: // Vector2
  7713. case 5: // Vector3
  7714. case 7: // Color Curves
  7715. case 10: // Quaternion
  7716. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7717. break;
  7718. }
  7719. }
  7720. }
  7721. return destination;
  7722. };
  7723. function getDirectStore(target) {
  7724. var classKey = target.getClassName();
  7725. if (!__decoratorInitialStore[classKey]) {
  7726. __decoratorInitialStore[classKey] = {};
  7727. }
  7728. return __decoratorInitialStore[classKey];
  7729. }
  7730. /**
  7731. * Return the list of properties flagged as serializable
  7732. * @param target: host object
  7733. */
  7734. function getMergedStore(target) {
  7735. var classKey = target.getClassName();
  7736. if (__mergedStore[classKey]) {
  7737. return __mergedStore[classKey];
  7738. }
  7739. __mergedStore[classKey] = {};
  7740. var store = __mergedStore[classKey];
  7741. var currentTarget = target;
  7742. var currentKey = classKey;
  7743. while (currentKey) {
  7744. var initialStore = __decoratorInitialStore[currentKey];
  7745. for (var property in initialStore) {
  7746. store[property] = initialStore[property];
  7747. }
  7748. var parent_1 = void 0;
  7749. var done = false;
  7750. do {
  7751. parent_1 = Object.getPrototypeOf(currentTarget);
  7752. if (!parent_1.getClassName) {
  7753. done = true;
  7754. break;
  7755. }
  7756. if (parent_1.getClassName() !== currentKey) {
  7757. break;
  7758. }
  7759. currentTarget = parent_1;
  7760. } while (parent_1);
  7761. if (done) {
  7762. break;
  7763. }
  7764. currentKey = parent_1.getClassName();
  7765. currentTarget = parent_1;
  7766. }
  7767. return store;
  7768. }
  7769. function generateSerializableMember(type, sourceName) {
  7770. return function (target, propertyKey) {
  7771. var classStore = getDirectStore(target);
  7772. if (!classStore[propertyKey]) {
  7773. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7774. }
  7775. };
  7776. }
  7777. function generateExpandMember(setCallback, targetKey) {
  7778. if (targetKey === void 0) { targetKey = null; }
  7779. return function (target, propertyKey) {
  7780. var key = targetKey || ("_" + propertyKey);
  7781. Object.defineProperty(target, propertyKey, {
  7782. get: function () {
  7783. return this[key];
  7784. },
  7785. set: function (value) {
  7786. if (this[key] === value) {
  7787. return;
  7788. }
  7789. this[key] = value;
  7790. target[setCallback].apply(this);
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. };
  7796. }
  7797. function expandToProperty(callback, targetKey) {
  7798. if (targetKey === void 0) { targetKey = null; }
  7799. return generateExpandMember(callback, targetKey);
  7800. }
  7801. BABYLON.expandToProperty = expandToProperty;
  7802. function serialize(sourceName) {
  7803. return generateSerializableMember(0, sourceName); // value member
  7804. }
  7805. BABYLON.serialize = serialize;
  7806. function serializeAsTexture(sourceName) {
  7807. return generateSerializableMember(1, sourceName); // texture member
  7808. }
  7809. BABYLON.serializeAsTexture = serializeAsTexture;
  7810. function serializeAsColor3(sourceName) {
  7811. return generateSerializableMember(2, sourceName); // color3 member
  7812. }
  7813. BABYLON.serializeAsColor3 = serializeAsColor3;
  7814. function serializeAsFresnelParameters(sourceName) {
  7815. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7816. }
  7817. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7818. function serializeAsVector2(sourceName) {
  7819. return generateSerializableMember(4, sourceName); // vector2 member
  7820. }
  7821. BABYLON.serializeAsVector2 = serializeAsVector2;
  7822. function serializeAsVector3(sourceName) {
  7823. return generateSerializableMember(5, sourceName); // vector3 member
  7824. }
  7825. BABYLON.serializeAsVector3 = serializeAsVector3;
  7826. function serializeAsMeshReference(sourceName) {
  7827. return generateSerializableMember(6, sourceName); // mesh reference member
  7828. }
  7829. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7830. function serializeAsColorCurves(sourceName) {
  7831. return generateSerializableMember(7, sourceName); // color curves
  7832. }
  7833. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7834. function serializeAsColor4(sourceName) {
  7835. return generateSerializableMember(8, sourceName); // color 4
  7836. }
  7837. BABYLON.serializeAsColor4 = serializeAsColor4;
  7838. function serializeAsImageProcessingConfiguration(sourceName) {
  7839. return generateSerializableMember(9, sourceName); // image processing
  7840. }
  7841. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7842. function serializeAsQuaternion(sourceName) {
  7843. return generateSerializableMember(10, sourceName); // quaternion member
  7844. }
  7845. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7846. /**
  7847. * Decorator used to define property that can be serialized as reference to a camera
  7848. * @param sourceName defines the name of the property to decorate
  7849. */
  7850. function serializeAsCameraReference(sourceName) {
  7851. return generateSerializableMember(11, sourceName); // camera reference member
  7852. }
  7853. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7854. var SerializationHelper = /** @class */ (function () {
  7855. function SerializationHelper() {
  7856. }
  7857. SerializationHelper.Serialize = function (entity, serializationObject) {
  7858. if (!serializationObject) {
  7859. serializationObject = {};
  7860. }
  7861. // Tags
  7862. if (BABYLON.Tags) {
  7863. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7864. }
  7865. var serializedProperties = getMergedStore(entity);
  7866. // Properties
  7867. for (var property in serializedProperties) {
  7868. var propertyDescriptor = serializedProperties[property];
  7869. var targetPropertyName = propertyDescriptor.sourceName || property;
  7870. var propertyType = propertyDescriptor.type;
  7871. var sourceProperty = entity[property];
  7872. if (sourceProperty !== undefined && sourceProperty !== null) {
  7873. switch (propertyType) {
  7874. case 0: // Value
  7875. serializationObject[targetPropertyName] = sourceProperty;
  7876. break;
  7877. case 1: // Texture
  7878. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7879. break;
  7880. case 2: // Color3
  7881. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7882. break;
  7883. case 3: // FresnelParameters
  7884. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7885. break;
  7886. case 4: // Vector2
  7887. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7888. break;
  7889. case 5: // Vector3
  7890. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7891. break;
  7892. case 6: // Mesh reference
  7893. serializationObject[targetPropertyName] = sourceProperty.id;
  7894. break;
  7895. case 7: // Color Curves
  7896. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7897. break;
  7898. case 8: // Color 4
  7899. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7900. break;
  7901. case 9: // Image Processing
  7902. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7903. break;
  7904. case 10: // Quaternion
  7905. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7906. break;
  7907. case 11: // Camera reference
  7908. serializationObject[targetPropertyName] = sourceProperty.id;
  7909. break;
  7910. }
  7911. }
  7912. }
  7913. return serializationObject;
  7914. };
  7915. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7916. if (rootUrl === void 0) { rootUrl = null; }
  7917. var destination = creationFunction();
  7918. if (!rootUrl) {
  7919. rootUrl = "";
  7920. }
  7921. // Tags
  7922. if (BABYLON.Tags) {
  7923. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7924. }
  7925. var classStore = getMergedStore(destination);
  7926. // Properties
  7927. for (var property in classStore) {
  7928. var propertyDescriptor = classStore[property];
  7929. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7930. var propertyType = propertyDescriptor.type;
  7931. if (sourceProperty !== undefined && sourceProperty !== null) {
  7932. var dest = destination;
  7933. switch (propertyType) {
  7934. case 0: // Value
  7935. dest[property] = sourceProperty;
  7936. break;
  7937. case 1: // Texture
  7938. if (scene) {
  7939. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7940. }
  7941. break;
  7942. case 2: // Color3
  7943. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7944. break;
  7945. case 3: // FresnelParameters
  7946. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7947. break;
  7948. case 4: // Vector2
  7949. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7950. break;
  7951. case 5: // Vector3
  7952. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7953. break;
  7954. case 6: // Mesh reference
  7955. if (scene) {
  7956. dest[property] = scene.getLastMeshByID(sourceProperty);
  7957. }
  7958. break;
  7959. case 7: // Color Curves
  7960. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7961. break;
  7962. case 8: // Color 4
  7963. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7964. break;
  7965. case 9: // Image Processing
  7966. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7967. break;
  7968. case 10: // Quaternion
  7969. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7970. break;
  7971. case 11: // Camera reference
  7972. if (scene) {
  7973. dest[property] = scene.getCameraByID(sourceProperty);
  7974. }
  7975. break;
  7976. }
  7977. }
  7978. }
  7979. return destination;
  7980. };
  7981. SerializationHelper.Clone = function (creationFunction, source) {
  7982. return _copySource(creationFunction, source, false);
  7983. };
  7984. SerializationHelper.Instanciate = function (creationFunction, source) {
  7985. return _copySource(creationFunction, source, true);
  7986. };
  7987. return SerializationHelper;
  7988. }());
  7989. BABYLON.SerializationHelper = SerializationHelper;
  7990. })(BABYLON || (BABYLON = {}));
  7991. //# sourceMappingURL=babylon.decorators.js.map
  7992. var BABYLON;
  7993. (function (BABYLON) {
  7994. /**
  7995. * Wrapper class for promise with external resolve and reject.
  7996. */
  7997. var Deferred = /** @class */ (function () {
  7998. /**
  7999. * Constructor for this deferred object.
  8000. */
  8001. function Deferred() {
  8002. var _this = this;
  8003. this.promise = new Promise(function (resolve, reject) {
  8004. _this._resolve = resolve;
  8005. _this._reject = reject;
  8006. });
  8007. }
  8008. Object.defineProperty(Deferred.prototype, "resolve", {
  8009. /**
  8010. * The resolve method of the promise associated with this deferred object.
  8011. */
  8012. get: function () {
  8013. return this._resolve;
  8014. },
  8015. enumerable: true,
  8016. configurable: true
  8017. });
  8018. Object.defineProperty(Deferred.prototype, "reject", {
  8019. /**
  8020. * The reject method of the promise associated with this deferred object.
  8021. */
  8022. get: function () {
  8023. return this._reject;
  8024. },
  8025. enumerable: true,
  8026. configurable: true
  8027. });
  8028. return Deferred;
  8029. }());
  8030. BABYLON.Deferred = Deferred;
  8031. })(BABYLON || (BABYLON = {}));
  8032. //# sourceMappingURL=babylon.deferred.js.map
  8033. var BABYLON;
  8034. (function (BABYLON) {
  8035. /**
  8036. * A class serves as a medium between the observable and its observers
  8037. */
  8038. var EventState = /** @class */ (function () {
  8039. /**
  8040. * Create a new EventState
  8041. * @param mask defines the mask associated with this state
  8042. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8043. * @param target defines the original target of the state
  8044. * @param currentTarget defines the current target of the state
  8045. */
  8046. function EventState(mask, skipNextObservers, target, currentTarget) {
  8047. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8048. this.initalize(mask, skipNextObservers, target, currentTarget);
  8049. }
  8050. /**
  8051. * Initialize the current event state
  8052. * @param mask defines the mask associated with this state
  8053. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8054. * @param target defines the original target of the state
  8055. * @param currentTarget defines the current target of the state
  8056. * @returns the current event state
  8057. */
  8058. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8059. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8060. this.mask = mask;
  8061. this.skipNextObservers = skipNextObservers;
  8062. this.target = target;
  8063. this.currentTarget = currentTarget;
  8064. return this;
  8065. };
  8066. return EventState;
  8067. }());
  8068. BABYLON.EventState = EventState;
  8069. /**
  8070. * Represent an Observer registered to a given Observable object.
  8071. */
  8072. var Observer = /** @class */ (function () {
  8073. /**
  8074. * Creates a new observer
  8075. * @param callback defines the callback to call when the observer is notified
  8076. * @param mask defines the mask of the observer (used to filter notifications)
  8077. * @param scope defines the current scope used to restore the JS context
  8078. */
  8079. function Observer(
  8080. /**
  8081. * Defines the callback to call when the observer is notified
  8082. */
  8083. callback,
  8084. /**
  8085. * Defines the mask of the observer (used to filter notifications)
  8086. */
  8087. mask,
  8088. /**
  8089. * Defines the current scope used to restore the JS context
  8090. */
  8091. scope) {
  8092. if (scope === void 0) { scope = null; }
  8093. this.callback = callback;
  8094. this.mask = mask;
  8095. this.scope = scope;
  8096. /** @hidden */
  8097. this._willBeUnregistered = false;
  8098. /**
  8099. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8100. */
  8101. this.unregisterOnNextCall = false;
  8102. }
  8103. return Observer;
  8104. }());
  8105. BABYLON.Observer = Observer;
  8106. /**
  8107. * Represent a list of observers registered to multiple Observables object.
  8108. */
  8109. var MultiObserver = /** @class */ (function () {
  8110. function MultiObserver() {
  8111. }
  8112. /**
  8113. * Release associated resources
  8114. */
  8115. MultiObserver.prototype.dispose = function () {
  8116. if (this._observers && this._observables) {
  8117. for (var index = 0; index < this._observers.length; index++) {
  8118. this._observables[index].remove(this._observers[index]);
  8119. }
  8120. }
  8121. this._observers = null;
  8122. this._observables = null;
  8123. };
  8124. /**
  8125. * Raise a callback when one of the observable will notify
  8126. * @param observables defines a list of observables to watch
  8127. * @param callback defines the callback to call on notification
  8128. * @param mask defines the mask used to filter notifications
  8129. * @param scope defines the current scope used to restore the JS context
  8130. * @returns the new MultiObserver
  8131. */
  8132. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8133. if (mask === void 0) { mask = -1; }
  8134. if (scope === void 0) { scope = null; }
  8135. var result = new MultiObserver();
  8136. result._observers = new Array();
  8137. result._observables = observables;
  8138. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8139. var observable = observables_1[_i];
  8140. var observer = observable.add(callback, mask, false, scope);
  8141. if (observer) {
  8142. result._observers.push(observer);
  8143. }
  8144. }
  8145. return result;
  8146. };
  8147. return MultiObserver;
  8148. }());
  8149. BABYLON.MultiObserver = MultiObserver;
  8150. /**
  8151. * The Observable class is a simple implementation of the Observable pattern.
  8152. *
  8153. * 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.
  8154. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8155. * 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).
  8156. * 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.
  8157. */
  8158. var Observable = /** @class */ (function () {
  8159. /**
  8160. * Creates a new observable
  8161. * @param onObserverAdded defines a callback to call when a new observer is added
  8162. */
  8163. function Observable(onObserverAdded) {
  8164. this._observers = new Array();
  8165. this._eventState = new EventState(0);
  8166. if (onObserverAdded) {
  8167. this._onObserverAdded = onObserverAdded;
  8168. }
  8169. }
  8170. /**
  8171. * Create a new Observer with the specified callback
  8172. * @param callback the callback that will be executed for that Observer
  8173. * @param mask the mask used to filter observers
  8174. * @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.
  8175. * @param scope optional scope for the callback to be called from
  8176. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8177. * @returns the new observer created for the callback
  8178. */
  8179. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8180. if (mask === void 0) { mask = -1; }
  8181. if (insertFirst === void 0) { insertFirst = false; }
  8182. if (scope === void 0) { scope = null; }
  8183. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8184. if (!callback) {
  8185. return null;
  8186. }
  8187. var observer = new Observer(callback, mask, scope);
  8188. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8189. if (insertFirst) {
  8190. this._observers.unshift(observer);
  8191. }
  8192. else {
  8193. this._observers.push(observer);
  8194. }
  8195. if (this._onObserverAdded) {
  8196. this._onObserverAdded(observer);
  8197. }
  8198. return observer;
  8199. };
  8200. /**
  8201. * Create a new Observer with the specified callback and unregisters after the next notification
  8202. * @param callback the callback that will be executed for that Observer
  8203. * @returns the new observer created for the callback
  8204. */
  8205. Observable.prototype.addOnce = function (callback) {
  8206. return this.add(callback, undefined, undefined, undefined, true);
  8207. };
  8208. /**
  8209. * Remove an Observer from the Observable object
  8210. * @param observer the instance of the Observer to remove
  8211. * @returns false if it doesn't belong to this Observable
  8212. */
  8213. Observable.prototype.remove = function (observer) {
  8214. if (!observer) {
  8215. return false;
  8216. }
  8217. var index = this._observers.indexOf(observer);
  8218. if (index !== -1) {
  8219. this._deferUnregister(observer);
  8220. return true;
  8221. }
  8222. return false;
  8223. };
  8224. /**
  8225. * Remove a callback from the Observable object
  8226. * @param callback the callback to remove
  8227. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8228. * @returns false if it doesn't belong to this Observable
  8229. */
  8230. Observable.prototype.removeCallback = function (callback, scope) {
  8231. for (var index = 0; index < this._observers.length; index++) {
  8232. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8233. this._deferUnregister(this._observers[index]);
  8234. return true;
  8235. }
  8236. }
  8237. return false;
  8238. };
  8239. Observable.prototype._deferUnregister = function (observer) {
  8240. var _this = this;
  8241. observer.unregisterOnNextCall = false;
  8242. observer._willBeUnregistered = true;
  8243. BABYLON.Tools.SetImmediate(function () {
  8244. _this._remove(observer);
  8245. });
  8246. };
  8247. // This should only be called when not iterating over _observers to avoid callback skipping.
  8248. // Removes an observer from the _observer Array.
  8249. Observable.prototype._remove = function (observer) {
  8250. if (!observer) {
  8251. return false;
  8252. }
  8253. var index = this._observers.indexOf(observer);
  8254. if (index !== -1) {
  8255. this._observers.splice(index, 1);
  8256. return true;
  8257. }
  8258. return false;
  8259. };
  8260. /**
  8261. * Notify all Observers by calling their respective callback with the given data
  8262. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8263. * @param eventData defines the data to send to all observers
  8264. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8265. * @param target defines the original target of the state
  8266. * @param currentTarget defines the current target of the state
  8267. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8268. */
  8269. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8270. if (mask === void 0) { mask = -1; }
  8271. if (!this._observers.length) {
  8272. return true;
  8273. }
  8274. var state = this._eventState;
  8275. state.mask = mask;
  8276. state.target = target;
  8277. state.currentTarget = currentTarget;
  8278. state.skipNextObservers = false;
  8279. state.lastReturnValue = eventData;
  8280. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8281. var obs = _a[_i];
  8282. if (obs._willBeUnregistered) {
  8283. continue;
  8284. }
  8285. if (obs.mask & mask) {
  8286. if (obs.scope) {
  8287. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8288. }
  8289. else {
  8290. state.lastReturnValue = obs.callback(eventData, state);
  8291. }
  8292. if (obs.unregisterOnNextCall) {
  8293. this._deferUnregister(obs);
  8294. }
  8295. }
  8296. if (state.skipNextObservers) {
  8297. return false;
  8298. }
  8299. }
  8300. return true;
  8301. };
  8302. /**
  8303. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8304. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8305. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8306. * and it is crucial that all callbacks will be executed.
  8307. * The order of the callbacks is kept, callbacks are not executed parallel.
  8308. *
  8309. * @param eventData The data to be sent to each callback
  8310. * @param mask is used to filter observers defaults to -1
  8311. * @param target defines the callback target (see EventState)
  8312. * @param currentTarget defines he current object in the bubbling phase
  8313. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8314. */
  8315. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8316. var _this = this;
  8317. if (mask === void 0) { mask = -1; }
  8318. // create an empty promise
  8319. var p = Promise.resolve(eventData);
  8320. // no observers? return this promise.
  8321. if (!this._observers.length) {
  8322. return p;
  8323. }
  8324. var state = this._eventState;
  8325. state.mask = mask;
  8326. state.target = target;
  8327. state.currentTarget = currentTarget;
  8328. state.skipNextObservers = false;
  8329. // execute one callback after another (not using Promise.all, the order is important)
  8330. this._observers.forEach(function (obs) {
  8331. if (state.skipNextObservers) {
  8332. return;
  8333. }
  8334. if (obs._willBeUnregistered) {
  8335. return;
  8336. }
  8337. if (obs.mask & mask) {
  8338. if (obs.scope) {
  8339. p = p.then(function (lastReturnedValue) {
  8340. state.lastReturnValue = lastReturnedValue;
  8341. return obs.callback.apply(obs.scope, [eventData, state]);
  8342. });
  8343. }
  8344. else {
  8345. p = p.then(function (lastReturnedValue) {
  8346. state.lastReturnValue = lastReturnedValue;
  8347. return obs.callback(eventData, state);
  8348. });
  8349. }
  8350. if (obs.unregisterOnNextCall) {
  8351. _this._deferUnregister(obs);
  8352. }
  8353. }
  8354. });
  8355. // return the eventData
  8356. return p.then(function () { return eventData; });
  8357. };
  8358. /**
  8359. * Notify a specific observer
  8360. * @param observer defines the observer to notify
  8361. * @param eventData defines the data to be sent to each callback
  8362. * @param mask is used to filter observers defaults to -1
  8363. */
  8364. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8365. if (mask === void 0) { mask = -1; }
  8366. var state = this._eventState;
  8367. state.mask = mask;
  8368. state.skipNextObservers = false;
  8369. observer.callback(eventData, state);
  8370. };
  8371. /**
  8372. * Gets a boolean indicating if the observable has at least one observer
  8373. * @returns true is the Observable has at least one Observer registered
  8374. */
  8375. Observable.prototype.hasObservers = function () {
  8376. return this._observers.length > 0;
  8377. };
  8378. /**
  8379. * Clear the list of observers
  8380. */
  8381. Observable.prototype.clear = function () {
  8382. this._observers = new Array();
  8383. this._onObserverAdded = null;
  8384. };
  8385. /**
  8386. * Clone the current observable
  8387. * @returns a new observable
  8388. */
  8389. Observable.prototype.clone = function () {
  8390. var result = new Observable();
  8391. result._observers = this._observers.slice(0);
  8392. return result;
  8393. };
  8394. /**
  8395. * Does this observable handles observer registered with a given mask
  8396. * @param mask defines the mask to be tested
  8397. * @return whether or not one observer registered with the given mask is handeled
  8398. **/
  8399. Observable.prototype.hasSpecificMask = function (mask) {
  8400. if (mask === void 0) { mask = -1; }
  8401. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8402. var obs = _a[_i];
  8403. if (obs.mask & mask || obs.mask === mask) {
  8404. return true;
  8405. }
  8406. }
  8407. return false;
  8408. };
  8409. return Observable;
  8410. }());
  8411. BABYLON.Observable = Observable;
  8412. })(BABYLON || (BABYLON = {}));
  8413. //# sourceMappingURL=babylon.observable.js.map
  8414. var BABYLON;
  8415. (function (BABYLON) {
  8416. var SmartArray = /** @class */ (function () {
  8417. function SmartArray(capacity) {
  8418. this.length = 0;
  8419. this.data = new Array(capacity);
  8420. this._id = SmartArray._GlobalId++;
  8421. }
  8422. SmartArray.prototype.push = function (value) {
  8423. this.data[this.length++] = value;
  8424. if (this.length > this.data.length) {
  8425. this.data.length *= 2;
  8426. }
  8427. };
  8428. SmartArray.prototype.forEach = function (func) {
  8429. for (var index = 0; index < this.length; index++) {
  8430. func(this.data[index]);
  8431. }
  8432. };
  8433. SmartArray.prototype.sort = function (compareFn) {
  8434. this.data.sort(compareFn);
  8435. };
  8436. SmartArray.prototype.reset = function () {
  8437. this.length = 0;
  8438. };
  8439. SmartArray.prototype.dispose = function () {
  8440. this.reset();
  8441. if (this.data) {
  8442. this.data.length = 0;
  8443. this.data = [];
  8444. }
  8445. };
  8446. SmartArray.prototype.concat = function (array) {
  8447. if (array.length === 0) {
  8448. return;
  8449. }
  8450. if (this.length + array.length > this.data.length) {
  8451. this.data.length = (this.length + array.length) * 2;
  8452. }
  8453. for (var index = 0; index < array.length; index++) {
  8454. this.data[this.length++] = (array.data || array)[index];
  8455. }
  8456. };
  8457. SmartArray.prototype.indexOf = function (value) {
  8458. var position = this.data.indexOf(value);
  8459. if (position >= this.length) {
  8460. return -1;
  8461. }
  8462. return position;
  8463. };
  8464. SmartArray.prototype.contains = function (value) {
  8465. return this.data.indexOf(value) !== -1;
  8466. };
  8467. // Statics
  8468. SmartArray._GlobalId = 0;
  8469. return SmartArray;
  8470. }());
  8471. BABYLON.SmartArray = SmartArray;
  8472. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8473. __extends(SmartArrayNoDuplicate, _super);
  8474. function SmartArrayNoDuplicate() {
  8475. var _this = _super !== null && _super.apply(this, arguments) || this;
  8476. _this._duplicateId = 0;
  8477. return _this;
  8478. }
  8479. SmartArrayNoDuplicate.prototype.push = function (value) {
  8480. _super.prototype.push.call(this, value);
  8481. if (!value.__smartArrayFlags) {
  8482. value.__smartArrayFlags = {};
  8483. }
  8484. value.__smartArrayFlags[this._id] = this._duplicateId;
  8485. };
  8486. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8487. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8488. return false;
  8489. }
  8490. this.push(value);
  8491. return true;
  8492. };
  8493. SmartArrayNoDuplicate.prototype.reset = function () {
  8494. _super.prototype.reset.call(this);
  8495. this._duplicateId++;
  8496. };
  8497. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8498. if (array.length === 0) {
  8499. return;
  8500. }
  8501. if (this.length + array.length > this.data.length) {
  8502. this.data.length = (this.length + array.length) * 2;
  8503. }
  8504. for (var index = 0; index < array.length; index++) {
  8505. var item = (array.data || array)[index];
  8506. this.pushNoDuplicate(item);
  8507. }
  8508. };
  8509. return SmartArrayNoDuplicate;
  8510. }(SmartArray));
  8511. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8512. })(BABYLON || (BABYLON = {}));
  8513. //# sourceMappingURL=babylon.smartArray.js.map
  8514. var BABYLON;
  8515. (function (BABYLON) {
  8516. /** Class used to store color gradient */
  8517. var ColorGradient = /** @class */ (function () {
  8518. function ColorGradient() {
  8519. }
  8520. /**
  8521. * Will get a color picked randomly between color1 and color2.
  8522. * If color2 is undefined then color1 will be used
  8523. * @param result defines the target Color4 to store the result in
  8524. */
  8525. ColorGradient.prototype.getColorToRef = function (result) {
  8526. if (!this.color2) {
  8527. result.copyFrom(this.color1);
  8528. return;
  8529. }
  8530. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8531. };
  8532. return ColorGradient;
  8533. }());
  8534. BABYLON.ColorGradient = ColorGradient;
  8535. /** Class used to store factor gradient */
  8536. var FactorGradient = /** @class */ (function () {
  8537. function FactorGradient() {
  8538. }
  8539. /**
  8540. * Will get a number picked randomly between factor1 and factor2.
  8541. * If factor2 is undefined then factor1 will be used
  8542. * @returns the picked number
  8543. */
  8544. FactorGradient.prototype.getFactor = function () {
  8545. if (this.factor2 === undefined) {
  8546. return this.factor1;
  8547. }
  8548. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8549. };
  8550. return FactorGradient;
  8551. }());
  8552. BABYLON.FactorGradient = FactorGradient;
  8553. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8554. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8555. var LoadFileError = /** @class */ (function (_super) {
  8556. __extends(LoadFileError, _super);
  8557. function LoadFileError(message, request) {
  8558. var _this = _super.call(this, message) || this;
  8559. _this.request = request;
  8560. _this.name = "LoadFileError";
  8561. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8562. return _this;
  8563. }
  8564. // Polyfill for Object.setPrototypeOf if necessary.
  8565. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8566. return LoadFileError;
  8567. }(Error));
  8568. BABYLON.LoadFileError = LoadFileError;
  8569. var RetryStrategy = /** @class */ (function () {
  8570. function RetryStrategy() {
  8571. }
  8572. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8573. if (maxRetries === void 0) { maxRetries = 3; }
  8574. if (baseInterval === void 0) { baseInterval = 500; }
  8575. return function (url, request, retryIndex) {
  8576. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8577. return -1;
  8578. }
  8579. return Math.pow(2, retryIndex) * baseInterval;
  8580. };
  8581. };
  8582. return RetryStrategy;
  8583. }());
  8584. BABYLON.RetryStrategy = RetryStrategy;
  8585. // Screenshots
  8586. var screenshotCanvas;
  8587. var cloneValue = function (source, destinationObject) {
  8588. if (!source)
  8589. return null;
  8590. if (source instanceof BABYLON.Mesh) {
  8591. return null;
  8592. }
  8593. if (source instanceof BABYLON.SubMesh) {
  8594. return source.clone(destinationObject);
  8595. }
  8596. else if (source.clone) {
  8597. return source.clone();
  8598. }
  8599. return null;
  8600. };
  8601. var Tools = /** @class */ (function () {
  8602. function Tools() {
  8603. }
  8604. /**
  8605. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8606. * @param u defines the coordinate on X axis
  8607. * @param v defines the coordinate on Y axis
  8608. * @param width defines the width of the source data
  8609. * @param height defines the height of the source data
  8610. * @param pixels defines the source byte array
  8611. * @param color defines the output color
  8612. */
  8613. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8614. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8615. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8616. var position = (wrappedU + wrappedV * width) * 4;
  8617. color.r = pixels[position] / 255;
  8618. color.g = pixels[position + 1] / 255;
  8619. color.b = pixels[position + 2] / 255;
  8620. color.a = pixels[position + 3] / 255;
  8621. };
  8622. /**
  8623. * Read the R component of a byte array at a specified coordinates (taking in account wrapping)
  8624. * @param u defines the coordinate on X axis
  8625. * @param v defines the coordinate on Y axis
  8626. * @param width defines the width of the source data
  8627. * @param height defines the height of the source data
  8628. * @param pixels defines the source byte array
  8629. * @returns the R value
  8630. */
  8631. Tools.FetchR = function (u, v, width, height, pixels) {
  8632. u = Math.abs(u) + 0.5;
  8633. v = Math.abs(v) + 0.5;
  8634. var wrappedU = ((u * width) % width) | 0;
  8635. var wrappedV = ((v * height) % height) | 0;
  8636. // let wrappedU = (Math.abs(u) - Math.floor(Math.abs(u))) * width | 0;
  8637. // let wrappedV = (Math.abs(v) - Math.floor(Math.abs(v))) * height | 0;
  8638. var position = (wrappedU + wrappedV * width) * 4;
  8639. return pixels[position] / 255;
  8640. };
  8641. /**
  8642. * Interpolates between a and b via alpha
  8643. * @param a The lower value (returned when alpha = 0)
  8644. * @param b The upper value (returned when alpha = 1)
  8645. * @param alpha The interpolation-factor
  8646. * @return The mixed value
  8647. */
  8648. Tools.Mix = function (a, b, alpha) {
  8649. return a * (1 - alpha) + b * alpha;
  8650. };
  8651. Tools.Instantiate = function (className) {
  8652. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8653. return Tools.RegisteredExternalClasses[className];
  8654. }
  8655. var arr = className.split(".");
  8656. var fn = (window || this);
  8657. for (var i = 0, len = arr.length; i < len; i++) {
  8658. fn = fn[arr[i]];
  8659. }
  8660. if (typeof fn !== "function") {
  8661. return null;
  8662. }
  8663. return fn;
  8664. };
  8665. /**
  8666. * Provides a slice function that will work even on IE
  8667. * @param data defines the array to slice
  8668. * @param start defines the start of the data (optional)
  8669. * @param end defines the end of the data (optional)
  8670. * @returns the new sliced array
  8671. */
  8672. Tools.Slice = function (data, start, end) {
  8673. if (data.slice) {
  8674. return data.slice(start, end);
  8675. }
  8676. return Array.prototype.slice.call(data, start, end);
  8677. };
  8678. Tools.SetImmediate = function (action) {
  8679. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8680. window.setImmediate(action);
  8681. }
  8682. else {
  8683. setTimeout(action, 1);
  8684. }
  8685. };
  8686. Tools.IsExponentOfTwo = function (value) {
  8687. var count = 1;
  8688. do {
  8689. count *= 2;
  8690. } while (count < value);
  8691. return count === value;
  8692. };
  8693. /**
  8694. * Returns the nearest 32-bit single precision float representation of a Number
  8695. * @param value A Number. If the parameter is of a different type, it will get converted
  8696. * to a number or to NaN if it cannot be converted
  8697. * @returns number
  8698. */
  8699. Tools.FloatRound = function (value) {
  8700. if (Math.fround) {
  8701. return Math.fround(value);
  8702. }
  8703. return (Tools._tmpFloatArray[0] = value);
  8704. };
  8705. /**
  8706. * Find the next highest power of two.
  8707. * @param x Number to start search from.
  8708. * @return Next highest power of two.
  8709. */
  8710. Tools.CeilingPOT = function (x) {
  8711. x--;
  8712. x |= x >> 1;
  8713. x |= x >> 2;
  8714. x |= x >> 4;
  8715. x |= x >> 8;
  8716. x |= x >> 16;
  8717. x++;
  8718. return x;
  8719. };
  8720. /**
  8721. * Find the next lowest power of two.
  8722. * @param x Number to start search from.
  8723. * @return Next lowest power of two.
  8724. */
  8725. Tools.FloorPOT = function (x) {
  8726. x = x | (x >> 1);
  8727. x = x | (x >> 2);
  8728. x = x | (x >> 4);
  8729. x = x | (x >> 8);
  8730. x = x | (x >> 16);
  8731. return x - (x >> 1);
  8732. };
  8733. /**
  8734. * Find the nearest power of two.
  8735. * @param x Number to start search from.
  8736. * @return Next nearest power of two.
  8737. */
  8738. Tools.NearestPOT = function (x) {
  8739. var c = Tools.CeilingPOT(x);
  8740. var f = Tools.FloorPOT(x);
  8741. return (c - x) > (x - f) ? f : c;
  8742. };
  8743. Tools.GetExponentOfTwo = function (value, max, mode) {
  8744. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8745. var pot;
  8746. switch (mode) {
  8747. case BABYLON.Engine.SCALEMODE_FLOOR:
  8748. pot = Tools.FloorPOT(value);
  8749. break;
  8750. case BABYLON.Engine.SCALEMODE_NEAREST:
  8751. pot = Tools.NearestPOT(value);
  8752. break;
  8753. case BABYLON.Engine.SCALEMODE_CEILING:
  8754. default:
  8755. pot = Tools.CeilingPOT(value);
  8756. break;
  8757. }
  8758. return Math.min(pot, max);
  8759. };
  8760. Tools.GetFilename = function (path) {
  8761. var index = path.lastIndexOf("/");
  8762. if (index < 0)
  8763. return path;
  8764. return path.substring(index + 1);
  8765. };
  8766. /**
  8767. * Extracts the "folder" part of a path (everything before the filename).
  8768. * @param uri The URI to extract the info from
  8769. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8770. * @returns The "folder" part of the path
  8771. */
  8772. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8773. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8774. var index = uri.lastIndexOf("/");
  8775. if (index < 0) {
  8776. if (returnUnchangedIfNoSlash) {
  8777. return uri;
  8778. }
  8779. return "";
  8780. }
  8781. return uri.substring(0, index + 1);
  8782. };
  8783. Tools.GetDOMTextContent = function (element) {
  8784. var result = "";
  8785. var child = element.firstChild;
  8786. while (child) {
  8787. if (child.nodeType === 3) {
  8788. result += child.textContent;
  8789. }
  8790. child = child.nextSibling;
  8791. }
  8792. return result;
  8793. };
  8794. Tools.ToDegrees = function (angle) {
  8795. return angle * 180 / Math.PI;
  8796. };
  8797. Tools.ToRadians = function (angle) {
  8798. return angle * Math.PI / 180;
  8799. };
  8800. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8801. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8802. var output = "";
  8803. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8804. var i = 0;
  8805. var bytes = new Uint8Array(buffer);
  8806. while (i < bytes.length) {
  8807. chr1 = bytes[i++];
  8808. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8809. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8810. enc1 = chr1 >> 2;
  8811. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8812. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8813. enc4 = chr3 & 63;
  8814. if (isNaN(chr2)) {
  8815. enc3 = enc4 = 64;
  8816. }
  8817. else if (isNaN(chr3)) {
  8818. enc4 = 64;
  8819. }
  8820. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8821. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8822. }
  8823. return "data:image/png;base64," + output;
  8824. };
  8825. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8826. if (bias === void 0) { bias = null; }
  8827. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8828. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8829. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8830. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8831. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8832. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8833. }
  8834. if (bias) {
  8835. minimum.x -= minimum.x * bias.x + bias.y;
  8836. minimum.y -= minimum.y * bias.x + bias.y;
  8837. minimum.z -= minimum.z * bias.x + bias.y;
  8838. maximum.x += maximum.x * bias.x + bias.y;
  8839. maximum.y += maximum.y * bias.x + bias.y;
  8840. maximum.z += maximum.z * bias.x + bias.y;
  8841. }
  8842. return {
  8843. minimum: minimum,
  8844. maximum: maximum
  8845. };
  8846. };
  8847. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8848. if (bias === void 0) { bias = null; }
  8849. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8850. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8851. if (!stride) {
  8852. stride = 3;
  8853. }
  8854. for (var index = start; index < start + count; index++) {
  8855. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8856. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8857. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8858. }
  8859. if (bias) {
  8860. minimum.x -= minimum.x * bias.x + bias.y;
  8861. minimum.y -= minimum.y * bias.x + bias.y;
  8862. minimum.z -= minimum.z * bias.x + bias.y;
  8863. maximum.x += maximum.x * bias.x + bias.y;
  8864. maximum.y += maximum.y * bias.x + bias.y;
  8865. maximum.z += maximum.z * bias.x + bias.y;
  8866. }
  8867. return {
  8868. minimum: minimum,
  8869. maximum: maximum
  8870. };
  8871. };
  8872. Tools.Vector2ArrayFeeder = function (array) {
  8873. return function (index) {
  8874. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8875. var length = isFloatArray ? array.length / 2 : array.length;
  8876. if (index >= length) {
  8877. return null;
  8878. }
  8879. if (isFloatArray) {
  8880. var fa = array;
  8881. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8882. }
  8883. var a = array;
  8884. return a[index];
  8885. };
  8886. };
  8887. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8888. if (bias === void 0) { bias = null; }
  8889. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8890. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8891. var i = 0;
  8892. var cur = feeder(i++);
  8893. while (cur) {
  8894. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8895. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8896. cur = feeder(i++);
  8897. }
  8898. if (bias) {
  8899. minimum.x -= minimum.x * bias.x + bias.y;
  8900. minimum.y -= minimum.y * bias.x + bias.y;
  8901. maximum.x += maximum.x * bias.x + bias.y;
  8902. maximum.y += maximum.y * bias.x + bias.y;
  8903. }
  8904. return {
  8905. minimum: minimum,
  8906. maximum: maximum
  8907. };
  8908. };
  8909. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8910. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8911. return null;
  8912. return Array.isArray(obj) ? obj : [obj];
  8913. };
  8914. // Misc.
  8915. Tools.GetPointerPrefix = function () {
  8916. var eventPrefix = "pointer";
  8917. // Check if pointer events are supported
  8918. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8919. eventPrefix = "mouse";
  8920. }
  8921. return eventPrefix;
  8922. };
  8923. /**
  8924. * @param func - the function to be called
  8925. * @param requester - the object that will request the next frame. Falls back to window.
  8926. */
  8927. Tools.QueueNewFrame = function (func, requester) {
  8928. if (!Tools.IsWindowObjectExist()) {
  8929. return setTimeout(func, 16);
  8930. }
  8931. if (!requester) {
  8932. requester = window;
  8933. }
  8934. if (requester.requestAnimationFrame) {
  8935. return requester.requestAnimationFrame(func);
  8936. }
  8937. else if (requester.msRequestAnimationFrame) {
  8938. return requester.msRequestAnimationFrame(func);
  8939. }
  8940. else if (requester.webkitRequestAnimationFrame) {
  8941. return requester.webkitRequestAnimationFrame(func);
  8942. }
  8943. else if (requester.mozRequestAnimationFrame) {
  8944. return requester.mozRequestAnimationFrame(func);
  8945. }
  8946. else if (requester.oRequestAnimationFrame) {
  8947. return requester.oRequestAnimationFrame(func);
  8948. }
  8949. else {
  8950. return window.setTimeout(func, 16);
  8951. }
  8952. };
  8953. Tools.RequestFullscreen = function (element) {
  8954. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8955. if (!requestFunction)
  8956. return;
  8957. requestFunction.call(element);
  8958. };
  8959. Tools.ExitFullscreen = function () {
  8960. if (document.exitFullscreen) {
  8961. document.exitFullscreen();
  8962. }
  8963. else if (document.mozCancelFullScreen) {
  8964. document.mozCancelFullScreen();
  8965. }
  8966. else if (document.webkitCancelFullScreen) {
  8967. document.webkitCancelFullScreen();
  8968. }
  8969. else if (document.msCancelFullScreen) {
  8970. document.msCancelFullScreen();
  8971. }
  8972. };
  8973. Tools.SetCorsBehavior = function (url, element) {
  8974. if (url && url.indexOf("data:") === 0) {
  8975. return;
  8976. }
  8977. if (Tools.CorsBehavior) {
  8978. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8979. element.crossOrigin = Tools.CorsBehavior;
  8980. }
  8981. else {
  8982. var result = Tools.CorsBehavior(url);
  8983. if (result) {
  8984. element.crossOrigin = result;
  8985. }
  8986. }
  8987. }
  8988. };
  8989. // External files
  8990. Tools.CleanUrl = function (url) {
  8991. url = url.replace(/#/mg, "%23");
  8992. return url;
  8993. };
  8994. /**
  8995. * Loads an image as an HTMLImageElement.
  8996. * @param input url string, ArrayBuffer, or Blob to load
  8997. * @param onLoad callback called when the image successfully loads
  8998. * @param onError callback called when the image fails to load
  8999. * @param database database for caching
  9000. * @returns the HTMLImageElement of the loaded image
  9001. */
  9002. Tools.LoadImage = function (input, onLoad, onError, database) {
  9003. var url;
  9004. var usingObjectURL = false;
  9005. if (input instanceof ArrayBuffer) {
  9006. url = URL.createObjectURL(new Blob([input]));
  9007. usingObjectURL = true;
  9008. }
  9009. else if (input instanceof Blob) {
  9010. url = URL.createObjectURL(input);
  9011. usingObjectURL = true;
  9012. }
  9013. else {
  9014. url = Tools.CleanUrl(input);
  9015. url = Tools.PreprocessUrl(input);
  9016. }
  9017. var img = new Image();
  9018. Tools.SetCorsBehavior(url, img);
  9019. var loadHandler = function () {
  9020. if (usingObjectURL && img.src) {
  9021. URL.revokeObjectURL(img.src);
  9022. }
  9023. img.removeEventListener("load", loadHandler);
  9024. img.removeEventListener("error", errorHandler);
  9025. onLoad(img);
  9026. };
  9027. var errorHandler = function (err) {
  9028. if (usingObjectURL && img.src) {
  9029. URL.revokeObjectURL(img.src);
  9030. }
  9031. img.removeEventListener("load", loadHandler);
  9032. img.removeEventListener("error", errorHandler);
  9033. Tools.Error("Error while trying to load image: " + input);
  9034. if (onError) {
  9035. onError("Error while trying to load image: " + input, err);
  9036. }
  9037. };
  9038. img.addEventListener("load", loadHandler);
  9039. img.addEventListener("error", errorHandler);
  9040. var noIndexedDB = function () {
  9041. img.src = url;
  9042. };
  9043. var loadFromIndexedDB = function () {
  9044. if (database) {
  9045. database.loadImageFromDB(url, img);
  9046. }
  9047. };
  9048. //ANY database to do!
  9049. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9050. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9051. }
  9052. else {
  9053. if (url.indexOf("file:") !== -1) {
  9054. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9055. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9056. try {
  9057. var blobURL;
  9058. try {
  9059. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9060. }
  9061. catch (ex) {
  9062. // Chrome doesn't support oneTimeOnly parameter
  9063. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9064. }
  9065. img.src = blobURL;
  9066. usingObjectURL = true;
  9067. }
  9068. catch (e) {
  9069. img.src = "";
  9070. }
  9071. return img;
  9072. }
  9073. }
  9074. noIndexedDB();
  9075. }
  9076. return img;
  9077. };
  9078. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9079. url = Tools.CleanUrl(url);
  9080. url = Tools.PreprocessUrl(url);
  9081. // If file and file input are set
  9082. if (url.indexOf("file:") !== -1) {
  9083. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9084. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9085. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9086. }
  9087. }
  9088. var loadUrl = Tools.BaseUrl + url;
  9089. var aborted = false;
  9090. var fileRequest = {
  9091. onCompleteObservable: new BABYLON.Observable(),
  9092. abort: function () { return aborted = true; },
  9093. };
  9094. var requestFile = function () {
  9095. var request = new XMLHttpRequest();
  9096. var retryHandle = null;
  9097. fileRequest.abort = function () {
  9098. aborted = true;
  9099. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9100. request.abort();
  9101. }
  9102. if (retryHandle !== null) {
  9103. clearTimeout(retryHandle);
  9104. retryHandle = null;
  9105. }
  9106. };
  9107. var retryLoop = function (retryIndex) {
  9108. request.open('GET', loadUrl, true);
  9109. if (useArrayBuffer) {
  9110. request.responseType = "arraybuffer";
  9111. }
  9112. if (onProgress) {
  9113. request.addEventListener("progress", onProgress);
  9114. }
  9115. var onLoadEnd = function () {
  9116. request.removeEventListener("loadend", onLoadEnd);
  9117. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9118. fileRequest.onCompleteObservable.clear();
  9119. };
  9120. request.addEventListener("loadend", onLoadEnd);
  9121. var onReadyStateChange = function () {
  9122. if (aborted) {
  9123. return;
  9124. }
  9125. // In case of undefined state in some browsers.
  9126. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9127. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9128. request.removeEventListener("readystatechange", onReadyStateChange);
  9129. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9130. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9131. return;
  9132. }
  9133. var retryStrategy = Tools.DefaultRetryStrategy;
  9134. if (retryStrategy) {
  9135. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9136. if (waitTime !== -1) {
  9137. // Prevent the request from completing for retry.
  9138. request.removeEventListener("loadend", onLoadEnd);
  9139. request = new XMLHttpRequest();
  9140. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9141. return;
  9142. }
  9143. }
  9144. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9145. if (onError) {
  9146. onError(request, e);
  9147. }
  9148. else {
  9149. throw e;
  9150. }
  9151. }
  9152. };
  9153. request.addEventListener("readystatechange", onReadyStateChange);
  9154. request.send();
  9155. };
  9156. retryLoop(0);
  9157. };
  9158. // Caching all files
  9159. if (database && database.enableSceneOffline) {
  9160. var noIndexedDB_1 = function (request) {
  9161. if (request && request.status > 400) {
  9162. if (onError) {
  9163. onError(request);
  9164. }
  9165. }
  9166. else {
  9167. if (!aborted) {
  9168. requestFile();
  9169. }
  9170. }
  9171. };
  9172. var loadFromIndexedDB = function () {
  9173. // TODO: database needs to support aborting and should return a IFileRequest
  9174. if (aborted) {
  9175. return;
  9176. }
  9177. if (database) {
  9178. database.loadFileFromDB(url, function (data) {
  9179. if (!aborted) {
  9180. onSuccess(data);
  9181. }
  9182. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9183. }, onProgress ? function (event) {
  9184. if (!aborted) {
  9185. onProgress(event);
  9186. }
  9187. } : undefined, noIndexedDB_1, useArrayBuffer);
  9188. }
  9189. };
  9190. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9191. }
  9192. else {
  9193. requestFile();
  9194. }
  9195. return fileRequest;
  9196. };
  9197. /**
  9198. * Load a script (identified by an url). When the url returns, the
  9199. * content of this file is added into a new script element, attached to the DOM (body element)
  9200. */
  9201. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9202. var head = document.getElementsByTagName('head')[0];
  9203. var script = document.createElement('script');
  9204. script.type = 'text/javascript';
  9205. script.src = scriptUrl;
  9206. script.onload = function () {
  9207. if (onSuccess) {
  9208. onSuccess();
  9209. }
  9210. };
  9211. script.onerror = function (e) {
  9212. if (onError) {
  9213. onError("Unable to load script '" + scriptUrl + "'", e);
  9214. }
  9215. };
  9216. head.appendChild(script);
  9217. };
  9218. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9219. var reader = new FileReader();
  9220. var request = {
  9221. onCompleteObservable: new BABYLON.Observable(),
  9222. abort: function () { return reader.abort(); },
  9223. };
  9224. reader.onloadend = function (e) {
  9225. request.onCompleteObservable.notifyObservers(request);
  9226. };
  9227. reader.onload = function (e) {
  9228. //target doesn't have result from ts 1.3
  9229. callback(e.target['result']);
  9230. };
  9231. reader.onprogress = progressCallback;
  9232. reader.readAsDataURL(fileToLoad);
  9233. return request;
  9234. };
  9235. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9236. var reader = new FileReader();
  9237. var request = {
  9238. onCompleteObservable: new BABYLON.Observable(),
  9239. abort: function () { return reader.abort(); },
  9240. };
  9241. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9242. reader.onerror = function (e) {
  9243. Tools.Log("Error while reading file: " + fileToLoad.name);
  9244. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9245. };
  9246. reader.onload = function (e) {
  9247. //target doesn't have result from ts 1.3
  9248. callback(e.target['result']);
  9249. };
  9250. if (progressCallBack) {
  9251. reader.onprogress = progressCallBack;
  9252. }
  9253. if (!useArrayBuffer) {
  9254. // Asynchronous read
  9255. reader.readAsText(fileToLoad);
  9256. }
  9257. else {
  9258. reader.readAsArrayBuffer(fileToLoad);
  9259. }
  9260. return request;
  9261. };
  9262. //returns a downloadable url to a file content.
  9263. Tools.FileAsURL = function (content) {
  9264. var fileBlob = new Blob([content]);
  9265. var url = window.URL || window.webkitURL;
  9266. var link = url.createObjectURL(fileBlob);
  9267. return link;
  9268. };
  9269. // Misc.
  9270. Tools.Format = function (value, decimals) {
  9271. if (decimals === void 0) { decimals = 2; }
  9272. return value.toFixed(decimals);
  9273. };
  9274. Tools.CheckExtends = function (v, min, max) {
  9275. if (v.x < min.x)
  9276. min.x = v.x;
  9277. if (v.y < min.y)
  9278. min.y = v.y;
  9279. if (v.z < min.z)
  9280. min.z = v.z;
  9281. if (v.x > max.x)
  9282. max.x = v.x;
  9283. if (v.y > max.y)
  9284. max.y = v.y;
  9285. if (v.z > max.z)
  9286. max.z = v.z;
  9287. };
  9288. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9289. for (var prop in source) {
  9290. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9291. continue;
  9292. }
  9293. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9294. continue;
  9295. }
  9296. var sourceValue = source[prop];
  9297. var typeOfSourceValue = typeof sourceValue;
  9298. if (typeOfSourceValue === "function") {
  9299. continue;
  9300. }
  9301. try {
  9302. if (typeOfSourceValue === "object") {
  9303. if (sourceValue instanceof Array) {
  9304. destination[prop] = [];
  9305. if (sourceValue.length > 0) {
  9306. if (typeof sourceValue[0] == "object") {
  9307. for (var index = 0; index < sourceValue.length; index++) {
  9308. var clonedValue = cloneValue(sourceValue[index], destination);
  9309. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9310. destination[prop].push(clonedValue);
  9311. }
  9312. }
  9313. }
  9314. else {
  9315. destination[prop] = sourceValue.slice(0);
  9316. }
  9317. }
  9318. }
  9319. else {
  9320. destination[prop] = cloneValue(sourceValue, destination);
  9321. }
  9322. }
  9323. else {
  9324. destination[prop] = sourceValue;
  9325. }
  9326. }
  9327. catch (e) {
  9328. // Just ignore error (it could be because of a read-only property)
  9329. }
  9330. }
  9331. };
  9332. Tools.IsEmpty = function (obj) {
  9333. for (var i in obj) {
  9334. if (obj.hasOwnProperty(i)) {
  9335. return false;
  9336. }
  9337. }
  9338. return true;
  9339. };
  9340. Tools.RegisterTopRootEvents = function (events) {
  9341. for (var index = 0; index < events.length; index++) {
  9342. var event = events[index];
  9343. window.addEventListener(event.name, event.handler, false);
  9344. try {
  9345. if (window.parent) {
  9346. window.parent.addEventListener(event.name, event.handler, false);
  9347. }
  9348. }
  9349. catch (e) {
  9350. // Silently fails...
  9351. }
  9352. }
  9353. };
  9354. Tools.UnregisterTopRootEvents = function (events) {
  9355. for (var index = 0; index < events.length; index++) {
  9356. var event = events[index];
  9357. window.removeEventListener(event.name, event.handler);
  9358. try {
  9359. if (window.parent) {
  9360. window.parent.removeEventListener(event.name, event.handler);
  9361. }
  9362. }
  9363. catch (e) {
  9364. // Silently fails...
  9365. }
  9366. }
  9367. };
  9368. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9369. if (mimeType === void 0) { mimeType = "image/png"; }
  9370. // Read the contents of the framebuffer
  9371. var numberOfChannelsByLine = width * 4;
  9372. var halfHeight = height / 2;
  9373. //Reading datas from WebGL
  9374. var data = engine.readPixels(0, 0, width, height);
  9375. //To flip image on Y axis.
  9376. for (var i = 0; i < halfHeight; i++) {
  9377. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9378. var currentCell = j + i * numberOfChannelsByLine;
  9379. var targetLine = height - i - 1;
  9380. var targetCell = j + targetLine * numberOfChannelsByLine;
  9381. var temp = data[currentCell];
  9382. data[currentCell] = data[targetCell];
  9383. data[targetCell] = temp;
  9384. }
  9385. }
  9386. // Create a 2D canvas to store the result
  9387. if (!screenshotCanvas) {
  9388. screenshotCanvas = document.createElement('canvas');
  9389. }
  9390. screenshotCanvas.width = width;
  9391. screenshotCanvas.height = height;
  9392. var context = screenshotCanvas.getContext('2d');
  9393. if (context) {
  9394. // Copy the pixels to a 2D canvas
  9395. var imageData = context.createImageData(width, height);
  9396. var castData = (imageData.data);
  9397. castData.set(data);
  9398. context.putImageData(imageData, 0, 0);
  9399. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9400. }
  9401. };
  9402. /**
  9403. * Converts the canvas data to blob.
  9404. * This acts as a polyfill for browsers not supporting the to blob function.
  9405. * @param canvas Defines the canvas to extract the data from
  9406. * @param successCallback Defines the callback triggered once the data are available
  9407. * @param mimeType Defines the mime type of the result
  9408. */
  9409. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9410. if (mimeType === void 0) { mimeType = "image/png"; }
  9411. // We need HTMLCanvasElement.toBlob for HD screenshots
  9412. if (!canvas.toBlob) {
  9413. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9414. canvas.toBlob = function (callback, type, quality) {
  9415. var _this = this;
  9416. setTimeout(function () {
  9417. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9418. for (var i = 0; i < len; i++) {
  9419. arr[i] = binStr.charCodeAt(i);
  9420. }
  9421. callback(new Blob([arr]));
  9422. });
  9423. };
  9424. }
  9425. canvas.toBlob(function (blob) {
  9426. successCallback(blob);
  9427. }, mimeType);
  9428. };
  9429. /**
  9430. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9431. * @param successCallback Defines the callback triggered once the data are available
  9432. * @param mimeType Defines the mime type of the result
  9433. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9434. */
  9435. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9436. if (mimeType === void 0) { mimeType = "image/png"; }
  9437. if (successCallback) {
  9438. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9439. successCallback(base64Image);
  9440. }
  9441. else {
  9442. this.ToBlob(screenshotCanvas, function (blob) {
  9443. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9444. if (("download" in document.createElement("a"))) {
  9445. if (!fileName) {
  9446. var date = new Date();
  9447. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9448. fileName = "screenshot_" + stringDate + ".png";
  9449. }
  9450. Tools.Download(blob, fileName);
  9451. }
  9452. else {
  9453. var url = URL.createObjectURL(blob);
  9454. var newWindow = window.open("");
  9455. if (!newWindow)
  9456. return;
  9457. var img = newWindow.document.createElement("img");
  9458. img.onload = function () {
  9459. // no longer need to read the blob so it's revoked
  9460. URL.revokeObjectURL(url);
  9461. };
  9462. img.src = url;
  9463. newWindow.document.body.appendChild(img);
  9464. }
  9465. }, mimeType);
  9466. }
  9467. };
  9468. /**
  9469. * Downloads a blob in the browser
  9470. * @param blob defines the blob to download
  9471. * @param fileName defines the name of the downloaded file
  9472. */
  9473. Tools.Download = function (blob, fileName) {
  9474. if (navigator && navigator.msSaveBlob) {
  9475. navigator.msSaveBlob(blob, fileName);
  9476. return;
  9477. }
  9478. var url = window.URL.createObjectURL(blob);
  9479. var a = document.createElement("a");
  9480. document.body.appendChild(a);
  9481. a.style.display = "none";
  9482. a.href = url;
  9483. a.download = fileName;
  9484. a.addEventListener("click", function () {
  9485. if (a.parentElement) {
  9486. a.parentElement.removeChild(a);
  9487. }
  9488. });
  9489. a.click();
  9490. window.URL.revokeObjectURL(url);
  9491. };
  9492. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9493. if (mimeType === void 0) { mimeType = "image/png"; }
  9494. var width;
  9495. var height;
  9496. // If a precision value is specified
  9497. if (size.precision) {
  9498. width = Math.round(engine.getRenderWidth() * size.precision);
  9499. height = Math.round(width / engine.getAspectRatio(camera));
  9500. }
  9501. else if (size.width && size.height) {
  9502. width = size.width;
  9503. height = size.height;
  9504. }
  9505. //If passing only width, computing height to keep display canvas ratio.
  9506. else if (size.width && !size.height) {
  9507. width = size.width;
  9508. height = Math.round(width / engine.getAspectRatio(camera));
  9509. }
  9510. //If passing only height, computing width to keep display canvas ratio.
  9511. else if (size.height && !size.width) {
  9512. height = size.height;
  9513. width = Math.round(height * engine.getAspectRatio(camera));
  9514. }
  9515. //Assuming here that "size" parameter is a number
  9516. else if (!isNaN(size)) {
  9517. height = size;
  9518. width = size;
  9519. }
  9520. else {
  9521. Tools.Error("Invalid 'size' parameter !");
  9522. return;
  9523. }
  9524. if (!screenshotCanvas) {
  9525. screenshotCanvas = document.createElement('canvas');
  9526. }
  9527. screenshotCanvas.width = width;
  9528. screenshotCanvas.height = height;
  9529. var renderContext = screenshotCanvas.getContext("2d");
  9530. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9531. var newWidth = width;
  9532. var newHeight = newWidth / ratio;
  9533. if (newHeight > height) {
  9534. newHeight = height;
  9535. newWidth = newHeight * ratio;
  9536. }
  9537. var offsetX = Math.max(0, width - newWidth) / 2;
  9538. var offsetY = Math.max(0, height - newHeight) / 2;
  9539. var renderingCanvas = engine.getRenderingCanvas();
  9540. if (renderContext && renderingCanvas) {
  9541. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9542. }
  9543. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9544. };
  9545. /**
  9546. * Generates an image screenshot from the specified camera.
  9547. *
  9548. * @param engine The engine to use for rendering
  9549. * @param camera The camera to use for rendering
  9550. * @param size This parameter can be set to a single number or to an object with the
  9551. * following (optional) properties: precision, width, height. If a single number is passed,
  9552. * it will be used for both width and height. If an object is passed, the screenshot size
  9553. * will be derived from the parameters. The precision property is a multiplier allowing
  9554. * rendering at a higher or lower resolution.
  9555. * @param successCallback The callback receives a single parameter which contains the
  9556. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9557. * src parameter of an <img> to display it.
  9558. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9559. * Check your browser for supported MIME types.
  9560. * @param samples Texture samples (default: 1)
  9561. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9562. * @param fileName A name for for the downloaded file.
  9563. * @constructor
  9564. */
  9565. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9566. if (mimeType === void 0) { mimeType = "image/png"; }
  9567. if (samples === void 0) { samples = 1; }
  9568. if (antialiasing === void 0) { antialiasing = false; }
  9569. var width;
  9570. var height;
  9571. //If a precision value is specified
  9572. if (size.precision) {
  9573. width = Math.round(engine.getRenderWidth() * size.precision);
  9574. height = Math.round(width / engine.getAspectRatio(camera));
  9575. size = { width: width, height: height };
  9576. }
  9577. else if (size.width && size.height) {
  9578. width = size.width;
  9579. height = size.height;
  9580. }
  9581. //If passing only width, computing height to keep display canvas ratio.
  9582. else if (size.width && !size.height) {
  9583. width = size.width;
  9584. height = Math.round(width / engine.getAspectRatio(camera));
  9585. size = { width: width, height: height };
  9586. }
  9587. //If passing only height, computing width to keep display canvas ratio.
  9588. else if (size.height && !size.width) {
  9589. height = size.height;
  9590. width = Math.round(height * engine.getAspectRatio(camera));
  9591. size = { width: width, height: height };
  9592. }
  9593. //Assuming here that "size" parameter is a number
  9594. else if (!isNaN(size)) {
  9595. height = size;
  9596. width = size;
  9597. }
  9598. else {
  9599. Tools.Error("Invalid 'size' parameter !");
  9600. return;
  9601. }
  9602. var scene = camera.getScene();
  9603. var previousCamera = null;
  9604. if (scene.activeCamera !== camera) {
  9605. previousCamera = scene.activeCamera;
  9606. scene.activeCamera = camera;
  9607. }
  9608. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9609. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9610. texture.renderList = null;
  9611. texture.samples = samples;
  9612. if (antialiasing) {
  9613. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9614. }
  9615. texture.onAfterRenderObservable.add(function () {
  9616. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9617. });
  9618. scene.incrementRenderId();
  9619. scene.resetCachedMaterial();
  9620. texture.render(true);
  9621. texture.dispose();
  9622. if (previousCamera) {
  9623. scene.activeCamera = previousCamera;
  9624. }
  9625. camera.getProjectionMatrix(true); // Force cache refresh;
  9626. };
  9627. // XHR response validator for local file scenario
  9628. Tools.ValidateXHRData = function (xhr, dataType) {
  9629. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9630. if (dataType === void 0) { dataType = 7; }
  9631. try {
  9632. if (dataType & 1) {
  9633. if (xhr.responseText && xhr.responseText.length > 0) {
  9634. return true;
  9635. }
  9636. else if (dataType === 1) {
  9637. return false;
  9638. }
  9639. }
  9640. if (dataType & 2) {
  9641. // Check header width and height since there is no "TGA" magic number
  9642. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9643. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9644. return true;
  9645. }
  9646. else if (dataType === 2) {
  9647. return false;
  9648. }
  9649. }
  9650. if (dataType & 4) {
  9651. // Check for the "DDS" magic number
  9652. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9653. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9654. return true;
  9655. }
  9656. else {
  9657. return false;
  9658. }
  9659. }
  9660. }
  9661. catch (e) {
  9662. // Global protection
  9663. }
  9664. return false;
  9665. };
  9666. /**
  9667. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9668. * Be aware Math.random() could cause collisions, but:
  9669. * "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"
  9670. */
  9671. Tools.RandomId = function () {
  9672. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9673. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9674. return v.toString(16);
  9675. });
  9676. };
  9677. /**
  9678. * Test if the given uri is a base64 string.
  9679. * @param uri The uri to test
  9680. * @return True if the uri is a base64 string or false otherwise.
  9681. */
  9682. Tools.IsBase64 = function (uri) {
  9683. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9684. };
  9685. /**
  9686. * Decode the given base64 uri.
  9687. * @param uri The uri to decode
  9688. * @return The decoded base64 data.
  9689. */
  9690. Tools.DecodeBase64 = function (uri) {
  9691. var decodedString = atob(uri.split(",")[1]);
  9692. var bufferLength = decodedString.length;
  9693. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9694. for (var i = 0; i < bufferLength; i++) {
  9695. bufferView[i] = decodedString.charCodeAt(i);
  9696. }
  9697. return bufferView.buffer;
  9698. };
  9699. Object.defineProperty(Tools, "NoneLogLevel", {
  9700. get: function () {
  9701. return Tools._NoneLogLevel;
  9702. },
  9703. enumerable: true,
  9704. configurable: true
  9705. });
  9706. Object.defineProperty(Tools, "MessageLogLevel", {
  9707. get: function () {
  9708. return Tools._MessageLogLevel;
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. Object.defineProperty(Tools, "WarningLogLevel", {
  9714. get: function () {
  9715. return Tools._WarningLogLevel;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Object.defineProperty(Tools, "ErrorLogLevel", {
  9721. get: function () {
  9722. return Tools._ErrorLogLevel;
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. Object.defineProperty(Tools, "AllLogLevel", {
  9728. get: function () {
  9729. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9730. },
  9731. enumerable: true,
  9732. configurable: true
  9733. });
  9734. Tools._AddLogEntry = function (entry) {
  9735. Tools._LogCache = entry + Tools._LogCache;
  9736. if (Tools.OnNewCacheEntry) {
  9737. Tools.OnNewCacheEntry(entry);
  9738. }
  9739. };
  9740. Tools._FormatMessage = function (message) {
  9741. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9742. var date = new Date();
  9743. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9744. };
  9745. Tools._LogDisabled = function (message) {
  9746. // nothing to do
  9747. };
  9748. Tools._LogEnabled = function (message) {
  9749. var formattedMessage = Tools._FormatMessage(message);
  9750. console.log("BJS - " + formattedMessage);
  9751. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9752. Tools._AddLogEntry(entry);
  9753. };
  9754. Tools._WarnDisabled = function (message) {
  9755. // nothing to do
  9756. };
  9757. Tools._WarnEnabled = function (message) {
  9758. var formattedMessage = Tools._FormatMessage(message);
  9759. console.warn("BJS - " + formattedMessage);
  9760. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9761. Tools._AddLogEntry(entry);
  9762. };
  9763. Tools._ErrorDisabled = function (message) {
  9764. // nothing to do
  9765. };
  9766. Tools._ErrorEnabled = function (message) {
  9767. Tools.errorsCount++;
  9768. var formattedMessage = Tools._FormatMessage(message);
  9769. console.error("BJS - " + formattedMessage);
  9770. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9771. Tools._AddLogEntry(entry);
  9772. };
  9773. Object.defineProperty(Tools, "LogCache", {
  9774. get: function () {
  9775. return Tools._LogCache;
  9776. },
  9777. enumerable: true,
  9778. configurable: true
  9779. });
  9780. Tools.ClearLogCache = function () {
  9781. Tools._LogCache = "";
  9782. Tools.errorsCount = 0;
  9783. };
  9784. Object.defineProperty(Tools, "LogLevels", {
  9785. set: function (level) {
  9786. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9787. Tools.Log = Tools._LogEnabled;
  9788. }
  9789. else {
  9790. Tools.Log = Tools._LogDisabled;
  9791. }
  9792. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9793. Tools.Warn = Tools._WarnEnabled;
  9794. }
  9795. else {
  9796. Tools.Warn = Tools._WarnDisabled;
  9797. }
  9798. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9799. Tools.Error = Tools._ErrorEnabled;
  9800. }
  9801. else {
  9802. Tools.Error = Tools._ErrorDisabled;
  9803. }
  9804. },
  9805. enumerable: true,
  9806. configurable: true
  9807. });
  9808. Tools.IsWindowObjectExist = function () {
  9809. return (typeof window) !== "undefined";
  9810. };
  9811. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9812. get: function () {
  9813. return Tools._PerformanceNoneLogLevel;
  9814. },
  9815. enumerable: true,
  9816. configurable: true
  9817. });
  9818. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9819. get: function () {
  9820. return Tools._PerformanceUserMarkLogLevel;
  9821. },
  9822. enumerable: true,
  9823. configurable: true
  9824. });
  9825. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9826. get: function () {
  9827. return Tools._PerformanceConsoleLogLevel;
  9828. },
  9829. enumerable: true,
  9830. configurable: true
  9831. });
  9832. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9833. set: function (level) {
  9834. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9835. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9836. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9837. return;
  9838. }
  9839. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9840. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9841. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9842. return;
  9843. }
  9844. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9845. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9851. };
  9852. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9853. };
  9854. Tools._StartUserMark = function (counterName, condition) {
  9855. if (condition === void 0) { condition = true; }
  9856. if (!Tools._performance) {
  9857. if (!Tools.IsWindowObjectExist()) {
  9858. return;
  9859. }
  9860. Tools._performance = window.performance;
  9861. }
  9862. if (!condition || !Tools._performance.mark) {
  9863. return;
  9864. }
  9865. Tools._performance.mark(counterName + "-Begin");
  9866. };
  9867. Tools._EndUserMark = function (counterName, condition) {
  9868. if (condition === void 0) { condition = true; }
  9869. if (!condition || !Tools._performance.mark) {
  9870. return;
  9871. }
  9872. Tools._performance.mark(counterName + "-End");
  9873. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9874. };
  9875. Tools._StartPerformanceConsole = function (counterName, condition) {
  9876. if (condition === void 0) { condition = true; }
  9877. if (!condition) {
  9878. return;
  9879. }
  9880. Tools._StartUserMark(counterName, condition);
  9881. if (console.time) {
  9882. console.time(counterName);
  9883. }
  9884. };
  9885. Tools._EndPerformanceConsole = function (counterName, condition) {
  9886. if (condition === void 0) { condition = true; }
  9887. if (!condition) {
  9888. return;
  9889. }
  9890. Tools._EndUserMark(counterName, condition);
  9891. if (console.time) {
  9892. console.timeEnd(counterName);
  9893. }
  9894. };
  9895. Object.defineProperty(Tools, "Now", {
  9896. get: function () {
  9897. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9898. return window.performance.now();
  9899. }
  9900. return Date.now();
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. /**
  9906. * This method will return the name of the class used to create the instance of the given object.
  9907. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9908. * @param object the object to get the class name from
  9909. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9910. */
  9911. Tools.GetClassName = function (object, isType) {
  9912. if (isType === void 0) { isType = false; }
  9913. var name = null;
  9914. if (!isType && object.getClassName) {
  9915. name = object.getClassName();
  9916. }
  9917. else {
  9918. if (object instanceof Object) {
  9919. var classObj = isType ? object : Object.getPrototypeOf(object);
  9920. name = classObj.constructor["__bjsclassName__"];
  9921. }
  9922. if (!name) {
  9923. name = typeof object;
  9924. }
  9925. }
  9926. return name;
  9927. };
  9928. Tools.First = function (array, predicate) {
  9929. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9930. var el = array_1[_i];
  9931. if (predicate(el)) {
  9932. return el;
  9933. }
  9934. }
  9935. return null;
  9936. };
  9937. /**
  9938. * This method will return the name of the full name of the class, including its owning module (if any).
  9939. * 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).
  9940. * @param object the object to get the class name from
  9941. * @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.
  9942. */
  9943. Tools.getFullClassName = function (object, isType) {
  9944. if (isType === void 0) { isType = false; }
  9945. var className = null;
  9946. var moduleName = null;
  9947. if (!isType && object.getClassName) {
  9948. className = object.getClassName();
  9949. }
  9950. else {
  9951. if (object instanceof Object) {
  9952. var classObj = isType ? object : Object.getPrototypeOf(object);
  9953. className = classObj.constructor["__bjsclassName__"];
  9954. moduleName = classObj.constructor["__bjsmoduleName__"];
  9955. }
  9956. if (!className) {
  9957. className = typeof object;
  9958. }
  9959. }
  9960. if (!className) {
  9961. return null;
  9962. }
  9963. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9964. };
  9965. /**
  9966. * 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.
  9967. * @param array
  9968. */
  9969. Tools.arrayOrStringFeeder = function (array) {
  9970. return function (index) {
  9971. if (index >= array.length) {
  9972. return null;
  9973. }
  9974. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9975. if (val && val.getHashCode) {
  9976. val = val.getHashCode();
  9977. }
  9978. if (typeof val === "string") {
  9979. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9980. }
  9981. return val;
  9982. };
  9983. };
  9984. /**
  9985. * Compute the hashCode of a stream of number
  9986. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9987. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9988. * @return the hash code computed
  9989. */
  9990. Tools.hashCodeFromStream = function (feeder) {
  9991. // Based from here: http://stackoverflow.com/a/7616484/802124
  9992. var hash = 0;
  9993. var index = 0;
  9994. var chr = feeder(index++);
  9995. while (chr != null) {
  9996. hash = ((hash << 5) - hash) + chr;
  9997. hash |= 0; // Convert to 32bit integer
  9998. chr = feeder(index++);
  9999. }
  10000. return hash;
  10001. };
  10002. /**
  10003. * Returns a promise that resolves after the given amount of time.
  10004. * @param delay Number of milliseconds to delay
  10005. * @returns Promise that resolves after the given amount of time
  10006. */
  10007. Tools.DelayAsync = function (delay) {
  10008. return new Promise(function (resolve) {
  10009. setTimeout(function () {
  10010. resolve();
  10011. }, delay);
  10012. });
  10013. };
  10014. /**
  10015. * Gets the current gradient from an array of IValueGradient
  10016. * @param ratio defines the current ratio to get
  10017. * @param gradients defines the array of IValueGradient
  10018. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10019. */
  10020. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10021. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10022. var currentGradient = gradients[gradientIndex];
  10023. var nextGradient = gradients[gradientIndex + 1];
  10024. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10025. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10026. updateFunc(currentGradient, nextGradient, scale);
  10027. }
  10028. }
  10029. };
  10030. Tools.BaseUrl = "";
  10031. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10032. /**
  10033. * Default behaviour for cors in the application.
  10034. * It can be a string if the expected behavior is identical in the entire app.
  10035. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10036. */
  10037. Tools.CorsBehavior = "anonymous";
  10038. Tools.UseFallbackTexture = true;
  10039. /**
  10040. * Use this object to register external classes like custom textures or material
  10041. * to allow the laoders to instantiate them
  10042. */
  10043. Tools.RegisteredExternalClasses = {};
  10044. // Used in case of a texture loading problem
  10045. 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";
  10046. Tools._tmpFloatArray = new Float32Array(1);
  10047. Tools.PreprocessUrl = function (url) {
  10048. return url;
  10049. };
  10050. // Logs
  10051. Tools._NoneLogLevel = 0;
  10052. Tools._MessageLogLevel = 1;
  10053. Tools._WarningLogLevel = 2;
  10054. Tools._ErrorLogLevel = 4;
  10055. Tools._LogCache = "";
  10056. Tools.errorsCount = 0;
  10057. Tools.Log = Tools._LogEnabled;
  10058. Tools.Warn = Tools._WarnEnabled;
  10059. Tools.Error = Tools._ErrorEnabled;
  10060. // Performances
  10061. Tools._PerformanceNoneLogLevel = 0;
  10062. Tools._PerformanceUserMarkLogLevel = 1;
  10063. Tools._PerformanceConsoleLogLevel = 2;
  10064. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10065. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10066. return Tools;
  10067. }());
  10068. BABYLON.Tools = Tools;
  10069. /**
  10070. * This class is used to track a performance counter which is number based.
  10071. * The user has access to many properties which give statistics of different nature
  10072. *
  10073. * The implementer can track two kinds of Performance Counter: time and count
  10074. * 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.
  10075. * 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.
  10076. */
  10077. var PerfCounter = /** @class */ (function () {
  10078. function PerfCounter() {
  10079. this._startMonitoringTime = 0;
  10080. this._min = 0;
  10081. this._max = 0;
  10082. this._average = 0;
  10083. this._lastSecAverage = 0;
  10084. this._current = 0;
  10085. this._totalValueCount = 0;
  10086. this._totalAccumulated = 0;
  10087. this._lastSecAccumulated = 0;
  10088. this._lastSecTime = 0;
  10089. this._lastSecValueCount = 0;
  10090. }
  10091. Object.defineProperty(PerfCounter.prototype, "min", {
  10092. /**
  10093. * Returns the smallest value ever
  10094. */
  10095. get: function () {
  10096. return this._min;
  10097. },
  10098. enumerable: true,
  10099. configurable: true
  10100. });
  10101. Object.defineProperty(PerfCounter.prototype, "max", {
  10102. /**
  10103. * Returns the biggest value ever
  10104. */
  10105. get: function () {
  10106. return this._max;
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Object.defineProperty(PerfCounter.prototype, "average", {
  10112. /**
  10113. * Returns the average value since the performance counter is running
  10114. */
  10115. get: function () {
  10116. return this._average;
  10117. },
  10118. enumerable: true,
  10119. configurable: true
  10120. });
  10121. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10122. /**
  10123. * Returns the average value of the last second the counter was monitored
  10124. */
  10125. get: function () {
  10126. return this._lastSecAverage;
  10127. },
  10128. enumerable: true,
  10129. configurable: true
  10130. });
  10131. Object.defineProperty(PerfCounter.prototype, "current", {
  10132. /**
  10133. * Returns the current value
  10134. */
  10135. get: function () {
  10136. return this._current;
  10137. },
  10138. enumerable: true,
  10139. configurable: true
  10140. });
  10141. Object.defineProperty(PerfCounter.prototype, "total", {
  10142. get: function () {
  10143. return this._totalAccumulated;
  10144. },
  10145. enumerable: true,
  10146. configurable: true
  10147. });
  10148. Object.defineProperty(PerfCounter.prototype, "count", {
  10149. get: function () {
  10150. return this._totalValueCount;
  10151. },
  10152. enumerable: true,
  10153. configurable: true
  10154. });
  10155. /**
  10156. * Call this method to start monitoring a new frame.
  10157. * 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.
  10158. */
  10159. PerfCounter.prototype.fetchNewFrame = function () {
  10160. this._totalValueCount++;
  10161. this._current = 0;
  10162. this._lastSecValueCount++;
  10163. };
  10164. /**
  10165. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10166. * @param newCount the count value to add to the monitored count
  10167. * @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.
  10168. */
  10169. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10170. if (!PerfCounter.Enabled) {
  10171. return;
  10172. }
  10173. this._current += newCount;
  10174. if (fetchResult) {
  10175. this._fetchResult();
  10176. }
  10177. };
  10178. /**
  10179. * Start monitoring this performance counter
  10180. */
  10181. PerfCounter.prototype.beginMonitoring = function () {
  10182. if (!PerfCounter.Enabled) {
  10183. return;
  10184. }
  10185. this._startMonitoringTime = Tools.Now;
  10186. };
  10187. /**
  10188. * Compute the time lapsed since the previous beginMonitoring() call.
  10189. * @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
  10190. */
  10191. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10192. if (newFrame === void 0) { newFrame = true; }
  10193. if (!PerfCounter.Enabled) {
  10194. return;
  10195. }
  10196. if (newFrame) {
  10197. this.fetchNewFrame();
  10198. }
  10199. var currentTime = Tools.Now;
  10200. this._current = currentTime - this._startMonitoringTime;
  10201. if (newFrame) {
  10202. this._fetchResult();
  10203. }
  10204. };
  10205. PerfCounter.prototype._fetchResult = function () {
  10206. this._totalAccumulated += this._current;
  10207. this._lastSecAccumulated += this._current;
  10208. // Min/Max update
  10209. this._min = Math.min(this._min, this._current);
  10210. this._max = Math.max(this._max, this._current);
  10211. this._average = this._totalAccumulated / this._totalValueCount;
  10212. // Reset last sec?
  10213. var now = Tools.Now;
  10214. if ((now - this._lastSecTime) > 1000) {
  10215. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10216. this._lastSecTime = now;
  10217. this._lastSecAccumulated = 0;
  10218. this._lastSecValueCount = 0;
  10219. }
  10220. };
  10221. PerfCounter.Enabled = true;
  10222. return PerfCounter;
  10223. }());
  10224. BABYLON.PerfCounter = PerfCounter;
  10225. /**
  10226. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10227. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10228. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10229. * @param name The name of the class, case should be preserved
  10230. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10231. */
  10232. function className(name, module) {
  10233. return function (target) {
  10234. target["__bjsclassName__"] = name;
  10235. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10236. };
  10237. }
  10238. BABYLON.className = className;
  10239. /**
  10240. * An implementation of a loop for asynchronous functions.
  10241. */
  10242. var AsyncLoop = /** @class */ (function () {
  10243. /**
  10244. * Constroctor.
  10245. * @param iterations the number of iterations.
  10246. * @param _fn the function to run each iteration
  10247. * @param _successCallback the callback that will be called upon succesful execution
  10248. * @param offset starting offset.
  10249. */
  10250. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10251. if (offset === void 0) { offset = 0; }
  10252. this.iterations = iterations;
  10253. this._fn = _fn;
  10254. this._successCallback = _successCallback;
  10255. this.index = offset - 1;
  10256. this._done = false;
  10257. }
  10258. /**
  10259. * Execute the next iteration. Must be called after the last iteration was finished.
  10260. */
  10261. AsyncLoop.prototype.executeNext = function () {
  10262. if (!this._done) {
  10263. if (this.index + 1 < this.iterations) {
  10264. ++this.index;
  10265. this._fn(this);
  10266. }
  10267. else {
  10268. this.breakLoop();
  10269. }
  10270. }
  10271. };
  10272. /**
  10273. * Break the loop and run the success callback.
  10274. */
  10275. AsyncLoop.prototype.breakLoop = function () {
  10276. this._done = true;
  10277. this._successCallback();
  10278. };
  10279. /**
  10280. * Helper function
  10281. */
  10282. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10283. if (offset === void 0) { offset = 0; }
  10284. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10285. loop.executeNext();
  10286. return loop;
  10287. };
  10288. /**
  10289. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10290. * @param iterations total number of iterations
  10291. * @param syncedIterations number of synchronous iterations in each async iteration.
  10292. * @param fn the function to call each iteration.
  10293. * @param callback a success call back that will be called when iterating stops.
  10294. * @param breakFunction a break condition (optional)
  10295. * @param timeout timeout settings for the setTimeout function. default - 0.
  10296. * @constructor
  10297. */
  10298. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10299. if (timeout === void 0) { timeout = 0; }
  10300. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10301. if (breakFunction && breakFunction())
  10302. loop.breakLoop();
  10303. else {
  10304. setTimeout(function () {
  10305. for (var i = 0; i < syncedIterations; ++i) {
  10306. var iteration = (loop.index * syncedIterations) + i;
  10307. if (iteration >= iterations)
  10308. break;
  10309. fn(iteration);
  10310. if (breakFunction && breakFunction()) {
  10311. loop.breakLoop();
  10312. break;
  10313. }
  10314. }
  10315. loop.executeNext();
  10316. }, timeout);
  10317. }
  10318. }, callback);
  10319. };
  10320. return AsyncLoop;
  10321. }());
  10322. BABYLON.AsyncLoop = AsyncLoop;
  10323. })(BABYLON || (BABYLON = {}));
  10324. //# sourceMappingURL=babylon.tools.js.map
  10325. var BABYLON;
  10326. (function (BABYLON) {
  10327. var PromiseStates;
  10328. (function (PromiseStates) {
  10329. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10330. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10331. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10332. })(PromiseStates || (PromiseStates = {}));
  10333. var FulFillmentAgregator = /** @class */ (function () {
  10334. function FulFillmentAgregator() {
  10335. this.count = 0;
  10336. this.target = 0;
  10337. this.results = [];
  10338. }
  10339. return FulFillmentAgregator;
  10340. }());
  10341. var InternalPromise = /** @class */ (function () {
  10342. function InternalPromise(resolver) {
  10343. var _this = this;
  10344. this._state = PromiseStates.Pending;
  10345. this._children = new Array();
  10346. this._rejectWasConsumed = false;
  10347. if (!resolver) {
  10348. return;
  10349. }
  10350. try {
  10351. resolver(function (value) {
  10352. _this._resolve(value);
  10353. }, function (reason) {
  10354. _this._reject(reason);
  10355. });
  10356. }
  10357. catch (e) {
  10358. this._reject(e);
  10359. }
  10360. }
  10361. Object.defineProperty(InternalPromise.prototype, "_result", {
  10362. get: function () {
  10363. return this._resultValue;
  10364. },
  10365. set: function (value) {
  10366. this._resultValue = value;
  10367. if (this._parent && this._parent._result === undefined) {
  10368. this._parent._result = value;
  10369. }
  10370. },
  10371. enumerable: true,
  10372. configurable: true
  10373. });
  10374. InternalPromise.prototype.catch = function (onRejected) {
  10375. return this.then(undefined, onRejected);
  10376. };
  10377. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10378. var _this = this;
  10379. var newPromise = new InternalPromise();
  10380. newPromise._onFulfilled = onFulfilled;
  10381. newPromise._onRejected = onRejected;
  10382. // Composition
  10383. this._children.push(newPromise);
  10384. newPromise._parent = this;
  10385. if (this._state !== PromiseStates.Pending) {
  10386. BABYLON.Tools.SetImmediate(function () {
  10387. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10388. var returnedValue = newPromise._resolve(_this._result);
  10389. if (returnedValue !== undefined && returnedValue !== null) {
  10390. if (returnedValue._state !== undefined) {
  10391. var returnedPromise = returnedValue;
  10392. newPromise._children.push(returnedPromise);
  10393. returnedPromise._parent = newPromise;
  10394. newPromise = returnedPromise;
  10395. }
  10396. else {
  10397. newPromise._result = returnedValue;
  10398. }
  10399. }
  10400. }
  10401. else {
  10402. newPromise._reject(_this._reason);
  10403. }
  10404. });
  10405. }
  10406. return newPromise;
  10407. };
  10408. InternalPromise.prototype._moveChildren = function (children) {
  10409. var _this = this;
  10410. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10411. this._children.forEach(function (child) {
  10412. child._parent = _this;
  10413. });
  10414. if (this._state === PromiseStates.Fulfilled) {
  10415. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10416. var child = _b[_i];
  10417. child._resolve(this._result);
  10418. }
  10419. }
  10420. else if (this._state === PromiseStates.Rejected) {
  10421. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10422. var child = _d[_c];
  10423. child._reject(this._reason);
  10424. }
  10425. }
  10426. var _a;
  10427. };
  10428. InternalPromise.prototype._resolve = function (value) {
  10429. try {
  10430. this._state = PromiseStates.Fulfilled;
  10431. var returnedValue = null;
  10432. if (this._onFulfilled) {
  10433. returnedValue = this._onFulfilled(value);
  10434. }
  10435. if (returnedValue !== undefined && returnedValue !== null) {
  10436. if (returnedValue._state !== undefined) {
  10437. // Transmit children
  10438. var returnedPromise = returnedValue;
  10439. returnedPromise._parent = this;
  10440. returnedPromise._moveChildren(this._children);
  10441. value = returnedPromise._result;
  10442. }
  10443. else {
  10444. value = returnedValue;
  10445. }
  10446. }
  10447. this._result = value;
  10448. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10449. var child = _a[_i];
  10450. child._resolve(value);
  10451. }
  10452. this._children.length = 0;
  10453. delete this._onFulfilled;
  10454. delete this._onRejected;
  10455. }
  10456. catch (e) {
  10457. this._reject(e, true);
  10458. }
  10459. };
  10460. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10461. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10462. this._state = PromiseStates.Rejected;
  10463. this._reason = reason;
  10464. if (this._onRejected && !onLocalThrow) {
  10465. try {
  10466. this._onRejected(reason);
  10467. this._rejectWasConsumed = true;
  10468. }
  10469. catch (e) {
  10470. reason = e;
  10471. }
  10472. }
  10473. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10474. var child = _a[_i];
  10475. if (this._rejectWasConsumed) {
  10476. child._resolve(null);
  10477. }
  10478. else {
  10479. child._reject(reason);
  10480. }
  10481. }
  10482. this._children.length = 0;
  10483. delete this._onFulfilled;
  10484. delete this._onRejected;
  10485. };
  10486. InternalPromise.resolve = function (value) {
  10487. var newPromise = new InternalPromise();
  10488. newPromise._resolve(value);
  10489. return newPromise;
  10490. };
  10491. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10492. promise.then(function (value) {
  10493. agregator.results[index] = value;
  10494. agregator.count++;
  10495. if (agregator.count === agregator.target) {
  10496. agregator.rootPromise._resolve(agregator.results);
  10497. }
  10498. return null;
  10499. }, function (reason) {
  10500. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10501. agregator.rootPromise._reject(reason);
  10502. }
  10503. });
  10504. };
  10505. InternalPromise.all = function (promises) {
  10506. var newPromise = new InternalPromise();
  10507. var agregator = new FulFillmentAgregator();
  10508. agregator.target = promises.length;
  10509. agregator.rootPromise = newPromise;
  10510. if (promises.length) {
  10511. for (var index = 0; index < promises.length; index++) {
  10512. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10513. }
  10514. }
  10515. else {
  10516. newPromise._resolve([]);
  10517. }
  10518. return newPromise;
  10519. };
  10520. InternalPromise.race = function (promises) {
  10521. var newPromise = new InternalPromise();
  10522. if (promises.length) {
  10523. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10524. var promise = promises_1[_i];
  10525. promise.then(function (value) {
  10526. if (newPromise) {
  10527. newPromise._resolve(value);
  10528. newPromise = null;
  10529. }
  10530. return null;
  10531. }, function (reason) {
  10532. if (newPromise) {
  10533. newPromise._reject(reason);
  10534. newPromise = null;
  10535. }
  10536. });
  10537. }
  10538. }
  10539. return newPromise;
  10540. };
  10541. return InternalPromise;
  10542. }());
  10543. /**
  10544. * Helper class that provides a small promise polyfill
  10545. */
  10546. var PromisePolyfill = /** @class */ (function () {
  10547. function PromisePolyfill() {
  10548. }
  10549. /**
  10550. * Static function used to check if the polyfill is required
  10551. * If this is the case then the function will inject the polyfill to window.Promise
  10552. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10553. */
  10554. PromisePolyfill.Apply = function (force) {
  10555. if (force === void 0) { force = false; }
  10556. if (force || typeof Promise === 'undefined') {
  10557. var root = window;
  10558. root.Promise = InternalPromise;
  10559. }
  10560. };
  10561. return PromisePolyfill;
  10562. }());
  10563. BABYLON.PromisePolyfill = PromisePolyfill;
  10564. })(BABYLON || (BABYLON = {}));
  10565. //# sourceMappingURL=babylon.promise.js.map
  10566. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10567. var BABYLON;
  10568. (function (BABYLON) {
  10569. /**
  10570. * Helper class to push actions to a pool of workers.
  10571. */
  10572. var WorkerPool = /** @class */ (function () {
  10573. /**
  10574. * Constructor
  10575. * @param workers Array of workers to use for actions
  10576. */
  10577. function WorkerPool(workers) {
  10578. this._pendingActions = new Array();
  10579. this._workerInfos = workers.map(function (worker) { return ({
  10580. worker: worker,
  10581. active: false
  10582. }); });
  10583. }
  10584. /**
  10585. * Terminates all workers and clears any pending actions.
  10586. */
  10587. WorkerPool.prototype.dispose = function () {
  10588. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10589. var workerInfo = _a[_i];
  10590. workerInfo.worker.terminate();
  10591. }
  10592. delete this._workerInfos;
  10593. delete this._pendingActions;
  10594. };
  10595. /**
  10596. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10597. * pended until a worker has completed its action.
  10598. * @param action The action to perform. Call onComplete when the action is complete.
  10599. */
  10600. WorkerPool.prototype.push = function (action) {
  10601. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10602. var workerInfo = _a[_i];
  10603. if (!workerInfo.active) {
  10604. this._execute(workerInfo, action);
  10605. return;
  10606. }
  10607. }
  10608. this._pendingActions.push(action);
  10609. };
  10610. WorkerPool.prototype._execute = function (workerInfo, action) {
  10611. var _this = this;
  10612. workerInfo.active = true;
  10613. action(workerInfo.worker, function () {
  10614. workerInfo.active = false;
  10615. var nextAction = _this._pendingActions.shift();
  10616. if (nextAction) {
  10617. _this._execute(workerInfo, nextAction);
  10618. }
  10619. });
  10620. };
  10621. return WorkerPool;
  10622. }());
  10623. BABYLON.WorkerPool = WorkerPool;
  10624. })(BABYLON || (BABYLON = {}));
  10625. //# sourceMappingURL=babylon.workerPool.js.map
  10626. var BABYLON;
  10627. (function (BABYLON) {
  10628. /**
  10629. * @hidden
  10630. **/
  10631. var _AlphaState = /** @class */ (function () {
  10632. /**
  10633. * Initializes the state.
  10634. */
  10635. function _AlphaState() {
  10636. this._isAlphaBlendDirty = false;
  10637. this._isBlendFunctionParametersDirty = false;
  10638. this._isBlendEquationParametersDirty = false;
  10639. this._isBlendConstantsDirty = false;
  10640. this._alphaBlend = false;
  10641. this._blendFunctionParameters = new Array(4);
  10642. this._blendEquationParameters = new Array(2);
  10643. this._blendConstants = new Array(4);
  10644. this.reset();
  10645. }
  10646. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10647. get: function () {
  10648. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10649. },
  10650. enumerable: true,
  10651. configurable: true
  10652. });
  10653. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10654. get: function () {
  10655. return this._alphaBlend;
  10656. },
  10657. set: function (value) {
  10658. if (this._alphaBlend === value) {
  10659. return;
  10660. }
  10661. this._alphaBlend = value;
  10662. this._isAlphaBlendDirty = true;
  10663. },
  10664. enumerable: true,
  10665. configurable: true
  10666. });
  10667. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10668. if (this._blendConstants[0] === r &&
  10669. this._blendConstants[1] === g &&
  10670. this._blendConstants[2] === b &&
  10671. this._blendConstants[3] === a) {
  10672. return;
  10673. }
  10674. this._blendConstants[0] = r;
  10675. this._blendConstants[1] = g;
  10676. this._blendConstants[2] = b;
  10677. this._blendConstants[3] = a;
  10678. this._isBlendConstantsDirty = true;
  10679. };
  10680. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10681. if (this._blendFunctionParameters[0] === value0 &&
  10682. this._blendFunctionParameters[1] === value1 &&
  10683. this._blendFunctionParameters[2] === value2 &&
  10684. this._blendFunctionParameters[3] === value3) {
  10685. return;
  10686. }
  10687. this._blendFunctionParameters[0] = value0;
  10688. this._blendFunctionParameters[1] = value1;
  10689. this._blendFunctionParameters[2] = value2;
  10690. this._blendFunctionParameters[3] = value3;
  10691. this._isBlendFunctionParametersDirty = true;
  10692. };
  10693. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10694. if (this._blendEquationParameters[0] === rgb &&
  10695. this._blendEquationParameters[1] === alpha) {
  10696. return;
  10697. }
  10698. this._blendEquationParameters[0] = rgb;
  10699. this._blendEquationParameters[1] = alpha;
  10700. this._isBlendEquationParametersDirty = true;
  10701. };
  10702. _AlphaState.prototype.reset = function () {
  10703. this._alphaBlend = false;
  10704. this._blendFunctionParameters[0] = null;
  10705. this._blendFunctionParameters[1] = null;
  10706. this._blendFunctionParameters[2] = null;
  10707. this._blendFunctionParameters[3] = null;
  10708. this._blendEquationParameters[0] = null;
  10709. this._blendEquationParameters[1] = null;
  10710. this._blendConstants[0] = null;
  10711. this._blendConstants[1] = null;
  10712. this._blendConstants[2] = null;
  10713. this._blendConstants[3] = null;
  10714. this._isAlphaBlendDirty = true;
  10715. this._isBlendFunctionParametersDirty = false;
  10716. this._isBlendEquationParametersDirty = false;
  10717. this._isBlendConstantsDirty = false;
  10718. };
  10719. _AlphaState.prototype.apply = function (gl) {
  10720. if (!this.isDirty) {
  10721. return;
  10722. }
  10723. // Alpha blend
  10724. if (this._isAlphaBlendDirty) {
  10725. if (this._alphaBlend) {
  10726. gl.enable(gl.BLEND);
  10727. }
  10728. else {
  10729. gl.disable(gl.BLEND);
  10730. }
  10731. this._isAlphaBlendDirty = false;
  10732. }
  10733. // Alpha function
  10734. if (this._isBlendFunctionParametersDirty) {
  10735. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10736. this._isBlendFunctionParametersDirty = false;
  10737. }
  10738. // Alpha equation
  10739. if (this._isBlendEquationParametersDirty) {
  10740. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10741. this._isBlendEquationParametersDirty = false;
  10742. }
  10743. // Constants
  10744. if (this._isBlendConstantsDirty) {
  10745. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10746. this._isBlendConstantsDirty = false;
  10747. }
  10748. };
  10749. return _AlphaState;
  10750. }());
  10751. BABYLON._AlphaState = _AlphaState;
  10752. })(BABYLON || (BABYLON = {}));
  10753. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10754. var BABYLON;
  10755. (function (BABYLON) {
  10756. /**
  10757. * @hidden
  10758. **/
  10759. var _DepthCullingState = /** @class */ (function () {
  10760. /**
  10761. * Initializes the state.
  10762. */
  10763. function _DepthCullingState() {
  10764. this._isDepthTestDirty = false;
  10765. this._isDepthMaskDirty = false;
  10766. this._isDepthFuncDirty = false;
  10767. this._isCullFaceDirty = false;
  10768. this._isCullDirty = false;
  10769. this._isZOffsetDirty = false;
  10770. this._isFrontFaceDirty = false;
  10771. this.reset();
  10772. }
  10773. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10774. get: function () {
  10775. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10776. },
  10777. enumerable: true,
  10778. configurable: true
  10779. });
  10780. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10781. get: function () {
  10782. return this._zOffset;
  10783. },
  10784. set: function (value) {
  10785. if (this._zOffset === value) {
  10786. return;
  10787. }
  10788. this._zOffset = value;
  10789. this._isZOffsetDirty = true;
  10790. },
  10791. enumerable: true,
  10792. configurable: true
  10793. });
  10794. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10795. get: function () {
  10796. return this._cullFace;
  10797. },
  10798. set: function (value) {
  10799. if (this._cullFace === value) {
  10800. return;
  10801. }
  10802. this._cullFace = value;
  10803. this._isCullFaceDirty = true;
  10804. },
  10805. enumerable: true,
  10806. configurable: true
  10807. });
  10808. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10809. get: function () {
  10810. return this._cull;
  10811. },
  10812. set: function (value) {
  10813. if (this._cull === value) {
  10814. return;
  10815. }
  10816. this._cull = value;
  10817. this._isCullDirty = true;
  10818. },
  10819. enumerable: true,
  10820. configurable: true
  10821. });
  10822. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10823. get: function () {
  10824. return this._depthFunc;
  10825. },
  10826. set: function (value) {
  10827. if (this._depthFunc === value) {
  10828. return;
  10829. }
  10830. this._depthFunc = value;
  10831. this._isDepthFuncDirty = true;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10837. get: function () {
  10838. return this._depthMask;
  10839. },
  10840. set: function (value) {
  10841. if (this._depthMask === value) {
  10842. return;
  10843. }
  10844. this._depthMask = value;
  10845. this._isDepthMaskDirty = true;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10851. get: function () {
  10852. return this._depthTest;
  10853. },
  10854. set: function (value) {
  10855. if (this._depthTest === value) {
  10856. return;
  10857. }
  10858. this._depthTest = value;
  10859. this._isDepthTestDirty = true;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10865. get: function () {
  10866. return this._frontFace;
  10867. },
  10868. set: function (value) {
  10869. if (this._frontFace === value) {
  10870. return;
  10871. }
  10872. this._frontFace = value;
  10873. this._isFrontFaceDirty = true;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. _DepthCullingState.prototype.reset = function () {
  10879. this._depthMask = true;
  10880. this._depthTest = true;
  10881. this._depthFunc = null;
  10882. this._cullFace = null;
  10883. this._cull = null;
  10884. this._zOffset = 0;
  10885. this._frontFace = null;
  10886. this._isDepthTestDirty = true;
  10887. this._isDepthMaskDirty = true;
  10888. this._isDepthFuncDirty = false;
  10889. this._isCullFaceDirty = false;
  10890. this._isCullDirty = false;
  10891. this._isZOffsetDirty = false;
  10892. this._isFrontFaceDirty = false;
  10893. };
  10894. _DepthCullingState.prototype.apply = function (gl) {
  10895. if (!this.isDirty) {
  10896. return;
  10897. }
  10898. // Cull
  10899. if (this._isCullDirty) {
  10900. if (this.cull) {
  10901. gl.enable(gl.CULL_FACE);
  10902. }
  10903. else {
  10904. gl.disable(gl.CULL_FACE);
  10905. }
  10906. this._isCullDirty = false;
  10907. }
  10908. // Cull face
  10909. if (this._isCullFaceDirty) {
  10910. gl.cullFace(this.cullFace);
  10911. this._isCullFaceDirty = false;
  10912. }
  10913. // Depth mask
  10914. if (this._isDepthMaskDirty) {
  10915. gl.depthMask(this.depthMask);
  10916. this._isDepthMaskDirty = false;
  10917. }
  10918. // Depth test
  10919. if (this._isDepthTestDirty) {
  10920. if (this.depthTest) {
  10921. gl.enable(gl.DEPTH_TEST);
  10922. }
  10923. else {
  10924. gl.disable(gl.DEPTH_TEST);
  10925. }
  10926. this._isDepthTestDirty = false;
  10927. }
  10928. // Depth func
  10929. if (this._isDepthFuncDirty) {
  10930. gl.depthFunc(this.depthFunc);
  10931. this._isDepthFuncDirty = false;
  10932. }
  10933. // zOffset
  10934. if (this._isZOffsetDirty) {
  10935. if (this.zOffset) {
  10936. gl.enable(gl.POLYGON_OFFSET_FILL);
  10937. gl.polygonOffset(this.zOffset, 0);
  10938. }
  10939. else {
  10940. gl.disable(gl.POLYGON_OFFSET_FILL);
  10941. }
  10942. this._isZOffsetDirty = false;
  10943. }
  10944. // Front face
  10945. if (this._isFrontFaceDirty) {
  10946. gl.frontFace(this.frontFace);
  10947. this._isFrontFaceDirty = false;
  10948. }
  10949. };
  10950. return _DepthCullingState;
  10951. }());
  10952. BABYLON._DepthCullingState = _DepthCullingState;
  10953. })(BABYLON || (BABYLON = {}));
  10954. //# sourceMappingURL=babylon.depthCullingState.js.map
  10955. var BABYLON;
  10956. (function (BABYLON) {
  10957. /**
  10958. * @hidden
  10959. **/
  10960. var _StencilState = /** @class */ (function () {
  10961. function _StencilState() {
  10962. this._isStencilTestDirty = false;
  10963. this._isStencilMaskDirty = false;
  10964. this._isStencilFuncDirty = false;
  10965. this._isStencilOpDirty = false;
  10966. this.reset();
  10967. }
  10968. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10969. get: function () {
  10970. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10976. get: function () {
  10977. return this._stencilFunc;
  10978. },
  10979. set: function (value) {
  10980. if (this._stencilFunc === value) {
  10981. return;
  10982. }
  10983. this._stencilFunc = value;
  10984. this._isStencilFuncDirty = true;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10990. get: function () {
  10991. return this._stencilFuncRef;
  10992. },
  10993. set: function (value) {
  10994. if (this._stencilFuncRef === value) {
  10995. return;
  10996. }
  10997. this._stencilFuncRef = value;
  10998. this._isStencilFuncDirty = true;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11004. get: function () {
  11005. return this._stencilFuncMask;
  11006. },
  11007. set: function (value) {
  11008. if (this._stencilFuncMask === value) {
  11009. return;
  11010. }
  11011. this._stencilFuncMask = value;
  11012. this._isStencilFuncDirty = true;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11018. get: function () {
  11019. return this._stencilOpStencilFail;
  11020. },
  11021. set: function (value) {
  11022. if (this._stencilOpStencilFail === value) {
  11023. return;
  11024. }
  11025. this._stencilOpStencilFail = value;
  11026. this._isStencilOpDirty = true;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11032. get: function () {
  11033. return this._stencilOpDepthFail;
  11034. },
  11035. set: function (value) {
  11036. if (this._stencilOpDepthFail === value) {
  11037. return;
  11038. }
  11039. this._stencilOpDepthFail = value;
  11040. this._isStencilOpDirty = true;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11046. get: function () {
  11047. return this._stencilOpStencilDepthPass;
  11048. },
  11049. set: function (value) {
  11050. if (this._stencilOpStencilDepthPass === value) {
  11051. return;
  11052. }
  11053. this._stencilOpStencilDepthPass = value;
  11054. this._isStencilOpDirty = true;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11060. get: function () {
  11061. return this._stencilMask;
  11062. },
  11063. set: function (value) {
  11064. if (this._stencilMask === value) {
  11065. return;
  11066. }
  11067. this._stencilMask = value;
  11068. this._isStencilMaskDirty = true;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11074. get: function () {
  11075. return this._stencilTest;
  11076. },
  11077. set: function (value) {
  11078. if (this._stencilTest === value) {
  11079. return;
  11080. }
  11081. this._stencilTest = value;
  11082. this._isStencilTestDirty = true;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. _StencilState.prototype.reset = function () {
  11088. this._stencilTest = false;
  11089. this._stencilMask = 0xFF;
  11090. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11091. this._stencilFuncRef = 1;
  11092. this._stencilFuncMask = 0xFF;
  11093. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11094. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11095. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11096. this._isStencilTestDirty = true;
  11097. this._isStencilMaskDirty = true;
  11098. this._isStencilFuncDirty = true;
  11099. this._isStencilOpDirty = true;
  11100. };
  11101. _StencilState.prototype.apply = function (gl) {
  11102. if (!this.isDirty) {
  11103. return;
  11104. }
  11105. // Stencil test
  11106. if (this._isStencilTestDirty) {
  11107. if (this.stencilTest) {
  11108. gl.enable(gl.STENCIL_TEST);
  11109. }
  11110. else {
  11111. gl.disable(gl.STENCIL_TEST);
  11112. }
  11113. this._isStencilTestDirty = false;
  11114. }
  11115. // Stencil mask
  11116. if (this._isStencilMaskDirty) {
  11117. gl.stencilMask(this.stencilMask);
  11118. this._isStencilMaskDirty = false;
  11119. }
  11120. // Stencil func
  11121. if (this._isStencilFuncDirty) {
  11122. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11123. this._isStencilFuncDirty = false;
  11124. }
  11125. // Stencil op
  11126. if (this._isStencilOpDirty) {
  11127. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11128. this._isStencilOpDirty = false;
  11129. }
  11130. };
  11131. return _StencilState;
  11132. }());
  11133. BABYLON._StencilState = _StencilState;
  11134. })(BABYLON || (BABYLON = {}));
  11135. //# sourceMappingURL=babylon.stencilState.js.map
  11136. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11137. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11138. s = arguments[i];
  11139. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11140. t[p] = s[p];
  11141. }
  11142. return t;
  11143. };
  11144. var BABYLON;
  11145. (function (BABYLON) {
  11146. /**
  11147. * Keeps track of all the buffer info used in engine.
  11148. */
  11149. var BufferPointer = /** @class */ (function () {
  11150. function BufferPointer() {
  11151. }
  11152. return BufferPointer;
  11153. }());
  11154. /**
  11155. * Interface for attribute information associated with buffer instanciation
  11156. */
  11157. var InstancingAttributeInfo = /** @class */ (function () {
  11158. function InstancingAttributeInfo() {
  11159. }
  11160. return InstancingAttributeInfo;
  11161. }());
  11162. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11163. /**
  11164. * Define options used to create a render target texture
  11165. */
  11166. var RenderTargetCreationOptions = /** @class */ (function () {
  11167. function RenderTargetCreationOptions() {
  11168. }
  11169. return RenderTargetCreationOptions;
  11170. }());
  11171. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11172. /**
  11173. * Define options used to create a depth texture
  11174. */
  11175. var DepthTextureCreationOptions = /** @class */ (function () {
  11176. function DepthTextureCreationOptions() {
  11177. }
  11178. return DepthTextureCreationOptions;
  11179. }());
  11180. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11181. /**
  11182. * Class used to describe the capabilities of the engine relatively to the current browser
  11183. */
  11184. var EngineCapabilities = /** @class */ (function () {
  11185. function EngineCapabilities() {
  11186. }
  11187. return EngineCapabilities;
  11188. }());
  11189. BABYLON.EngineCapabilities = EngineCapabilities;
  11190. /**
  11191. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11192. */
  11193. var Engine = /** @class */ (function () {
  11194. /**
  11195. * Creates a new engine
  11196. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11197. * @param antialias defines enable antialiasing (default: false)
  11198. * @param options defines further options to be sent to the getContext() function
  11199. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11200. */
  11201. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11202. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11203. var _this = this;
  11204. // Public members
  11205. /**
  11206. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11207. */
  11208. this.forcePOTTextures = false;
  11209. /**
  11210. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11211. */
  11212. this.isFullscreen = false;
  11213. /**
  11214. * Gets a boolean indicating if the pointer is currently locked
  11215. */
  11216. this.isPointerLock = false;
  11217. /**
  11218. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11219. */
  11220. this.cullBackFaces = true;
  11221. /**
  11222. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11223. */
  11224. this.renderEvenInBackground = true;
  11225. /**
  11226. * Gets or sets a boolean indicating that cache can be kept between frames
  11227. */
  11228. this.preventCacheWipeBetweenFrames = false;
  11229. /**
  11230. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11231. **/
  11232. this.enableOfflineSupport = false;
  11233. /**
  11234. * 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)
  11235. **/
  11236. this.disableManifestCheck = false;
  11237. /**
  11238. * Gets the list of created scenes
  11239. */
  11240. this.scenes = new Array();
  11241. /**
  11242. * Gets the list of created postprocesses
  11243. */
  11244. this.postProcesses = new Array();
  11245. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11246. this.validateShaderPrograms = false;
  11247. // Observables
  11248. /**
  11249. * Observable event triggered each time the rendering canvas is resized
  11250. */
  11251. this.onResizeObservable = new BABYLON.Observable();
  11252. /**
  11253. * Observable event triggered each time the canvas loses focus
  11254. */
  11255. this.onCanvasBlurObservable = new BABYLON.Observable();
  11256. /**
  11257. * Observable event triggered each time the canvas gains focus
  11258. */
  11259. this.onCanvasFocusObservable = new BABYLON.Observable();
  11260. /**
  11261. * Observable event triggered each time the canvas receives pointerout event
  11262. */
  11263. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11264. /**
  11265. * Observable event triggered before each texture is initialized
  11266. */
  11267. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11268. //WebVR
  11269. this._vrDisplay = undefined;
  11270. this._vrSupported = false;
  11271. this._vrExclusivePointerMode = false;
  11272. // Uniform buffers list
  11273. /**
  11274. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11275. */
  11276. this.disableUniformBuffers = false;
  11277. /** @hidden */
  11278. this._uniformBuffers = new Array();
  11279. // Observables
  11280. /**
  11281. * Observable raised when the engine begins a new frame
  11282. */
  11283. this.onBeginFrameObservable = new BABYLON.Observable();
  11284. /**
  11285. * Observable raised when the engine ends the current frame
  11286. */
  11287. this.onEndFrameObservable = new BABYLON.Observable();
  11288. /**
  11289. * Observable raised when the engine is about to compile a shader
  11290. */
  11291. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11292. /**
  11293. * Observable raised when the engine has jsut compiled a shader
  11294. */
  11295. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11296. this._windowIsBackground = false;
  11297. this._webGLVersion = 1.0;
  11298. /** @hidden */
  11299. this._badOS = false;
  11300. /** @hidden */
  11301. this._badDesktopOS = false;
  11302. /**
  11303. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11304. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11305. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11306. */
  11307. this.disableTextureBindingOptimization = false;
  11308. /**
  11309. * Observable signaled when VR display mode changes
  11310. */
  11311. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11312. /**
  11313. * Observable signaled when VR request present is complete
  11314. */
  11315. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11316. /**
  11317. * Observable signaled when VR request present starts
  11318. */
  11319. this.onVRRequestPresentStart = new BABYLON.Observable();
  11320. this._colorWrite = true;
  11321. /** @hidden */
  11322. this._drawCalls = new BABYLON.PerfCounter();
  11323. /** @hidden */
  11324. this._textureCollisions = new BABYLON.PerfCounter();
  11325. this._renderingQueueLaunched = false;
  11326. this._activeRenderLoops = new Array();
  11327. // Deterministic lockstepMaxSteps
  11328. this._deterministicLockstep = false;
  11329. this._lockstepMaxSteps = 4;
  11330. // Lost context
  11331. /**
  11332. * Observable signaled when a context lost event is raised
  11333. */
  11334. this.onContextLostObservable = new BABYLON.Observable();
  11335. /**
  11336. * Observable signaled when a context restored event is raised
  11337. */
  11338. this.onContextRestoredObservable = new BABYLON.Observable();
  11339. this._contextWasLost = false;
  11340. this._doNotHandleContextLost = false;
  11341. // FPS
  11342. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11343. this._fps = 60;
  11344. this._deltaTime = 0;
  11345. /**
  11346. * Turn this value on if you want to pause FPS computation when in background
  11347. */
  11348. this.disablePerformanceMonitorInBackground = false;
  11349. // States
  11350. /** @hidden */
  11351. this._depthCullingState = new BABYLON._DepthCullingState();
  11352. /** @hidden */
  11353. this._stencilState = new BABYLON._StencilState();
  11354. /** @hidden */
  11355. this._alphaState = new BABYLON._AlphaState();
  11356. /** @hidden */
  11357. this._alphaMode = Engine.ALPHA_DISABLE;
  11358. // Cache
  11359. this._internalTexturesCache = new Array();
  11360. /** @hidden */
  11361. this._activeChannel = 0;
  11362. this._currentTextureChannel = -1;
  11363. /** @hidden */
  11364. this._boundTexturesCache = {};
  11365. this._compiledEffects = {};
  11366. this._vertexAttribArraysEnabled = [];
  11367. this._uintIndicesCurrentlySet = false;
  11368. this._currentBoundBuffer = new Array();
  11369. /** @hidden */
  11370. this._currentFramebuffer = null;
  11371. this._currentBufferPointers = new Array();
  11372. this._currentInstanceLocations = new Array();
  11373. this._currentInstanceBuffers = new Array();
  11374. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11375. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11376. this._vaoRecordInProgress = false;
  11377. this._mustWipeVertexAttributes = false;
  11378. this._nextFreeTextureSlots = new Array();
  11379. this._maxSimultaneousTextures = 0;
  11380. this._activeRequests = new Array();
  11381. // Hardware supported Compressed Textures
  11382. this._texturesSupported = new Array();
  11383. /**
  11384. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11385. */
  11386. this.premultipliedAlpha = true;
  11387. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11388. this._onVRFullScreenTriggered = function () {
  11389. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11390. //get the old size before we change
  11391. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11392. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11393. //get the width and height, change the render size
  11394. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11395. _this.setHardwareScalingLevel(1);
  11396. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11397. }
  11398. else {
  11399. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11400. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11401. }
  11402. };
  11403. this._unpackFlipYCached = null;
  11404. this._boundUniforms = {};
  11405. // Register promises
  11406. BABYLON.PromisePolyfill.Apply();
  11407. var canvas = null;
  11408. Engine.Instances.push(this);
  11409. if (!canvasOrContext) {
  11410. return;
  11411. }
  11412. options = options || {};
  11413. if (canvasOrContext.getContext) {
  11414. canvas = canvasOrContext;
  11415. this._renderingCanvas = canvas;
  11416. if (antialias != null) {
  11417. options.antialias = antialias;
  11418. }
  11419. if (options.deterministicLockstep === undefined) {
  11420. options.deterministicLockstep = false;
  11421. }
  11422. if (options.lockstepMaxSteps === undefined) {
  11423. options.lockstepMaxSteps = 4;
  11424. }
  11425. if (options.preserveDrawingBuffer === undefined) {
  11426. options.preserveDrawingBuffer = false;
  11427. }
  11428. if (options.audioEngine === undefined) {
  11429. options.audioEngine = true;
  11430. }
  11431. if (options.stencil === undefined) {
  11432. options.stencil = true;
  11433. }
  11434. if (options.premultipliedAlpha === false) {
  11435. this.premultipliedAlpha = false;
  11436. }
  11437. this._deterministicLockstep = options.deterministicLockstep;
  11438. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11439. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11440. // Exceptions
  11441. if (navigator && navigator.userAgent) {
  11442. var ua = navigator.userAgent;
  11443. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11444. var exception = _a[_i];
  11445. var key = exception.key;
  11446. var targets = exception.targets;
  11447. if (ua.indexOf(key) > -1) {
  11448. if (exception.capture && exception.captureConstraint) {
  11449. var capture = exception.capture;
  11450. var constraint = exception.captureConstraint;
  11451. var regex = new RegExp(capture);
  11452. var matches = regex.exec(ua);
  11453. if (matches && matches.length > 0) {
  11454. var capturedValue = parseInt(matches[matches.length - 1]);
  11455. if (capturedValue >= constraint) {
  11456. continue;
  11457. }
  11458. }
  11459. }
  11460. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11461. var target = targets_1[_b];
  11462. switch (target) {
  11463. case "uniformBuffer":
  11464. this.disableUniformBuffers = true;
  11465. break;
  11466. case "textureBindingOptimization":
  11467. this.disableTextureBindingOptimization = true;
  11468. break;
  11469. }
  11470. }
  11471. }
  11472. }
  11473. }
  11474. // GL
  11475. if (!options.disableWebGL2Support) {
  11476. try {
  11477. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11478. if (this._gl) {
  11479. this._webGLVersion = 2.0;
  11480. }
  11481. }
  11482. catch (e) {
  11483. // Do nothing
  11484. }
  11485. }
  11486. if (!this._gl) {
  11487. if (!canvas) {
  11488. throw new Error("The provided canvas is null or undefined.");
  11489. }
  11490. try {
  11491. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11492. }
  11493. catch (e) {
  11494. throw new Error("WebGL not supported");
  11495. }
  11496. }
  11497. if (!this._gl) {
  11498. throw new Error("WebGL not supported");
  11499. }
  11500. this._onCanvasFocus = function () {
  11501. _this.onCanvasFocusObservable.notifyObservers(_this);
  11502. };
  11503. this._onCanvasBlur = function () {
  11504. _this.onCanvasBlurObservable.notifyObservers(_this);
  11505. };
  11506. canvas.addEventListener("focus", this._onCanvasFocus);
  11507. canvas.addEventListener("blur", this._onCanvasBlur);
  11508. this._onBlur = function () {
  11509. if (_this.disablePerformanceMonitorInBackground) {
  11510. _this._performanceMonitor.disable();
  11511. }
  11512. _this._windowIsBackground = true;
  11513. };
  11514. this._onFocus = function () {
  11515. if (_this.disablePerformanceMonitorInBackground) {
  11516. _this._performanceMonitor.enable();
  11517. }
  11518. _this._windowIsBackground = false;
  11519. };
  11520. this._onCanvasPointerOut = function (ev) {
  11521. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11522. };
  11523. window.addEventListener("blur", this._onBlur);
  11524. window.addEventListener("focus", this._onFocus);
  11525. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11526. // Context lost
  11527. if (!this._doNotHandleContextLost) {
  11528. this._onContextLost = function (evt) {
  11529. evt.preventDefault();
  11530. _this._contextWasLost = true;
  11531. BABYLON.Tools.Warn("WebGL context lost.");
  11532. _this.onContextLostObservable.notifyObservers(_this);
  11533. };
  11534. this._onContextRestored = function (evt) {
  11535. // Adding a timeout to avoid race condition at browser level
  11536. setTimeout(function () {
  11537. // Rebuild gl context
  11538. _this._initGLContext();
  11539. // Rebuild effects
  11540. _this._rebuildEffects();
  11541. // Rebuild textures
  11542. _this._rebuildInternalTextures();
  11543. // Rebuild buffers
  11544. _this._rebuildBuffers();
  11545. // Cache
  11546. _this.wipeCaches(true);
  11547. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11548. _this.onContextRestoredObservable.notifyObservers(_this);
  11549. _this._contextWasLost = false;
  11550. }, 0);
  11551. };
  11552. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11553. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11554. }
  11555. }
  11556. else {
  11557. this._gl = canvasOrContext;
  11558. this._renderingCanvas = this._gl.canvas;
  11559. if (this._gl.renderbufferStorageMultisample) {
  11560. this._webGLVersion = 2.0;
  11561. }
  11562. options.stencil = this._gl.getContextAttributes().stencil;
  11563. }
  11564. // Viewport
  11565. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11566. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11567. this.resize();
  11568. this._isStencilEnable = options.stencil ? true : false;
  11569. this._initGLContext();
  11570. if (canvas) {
  11571. // Fullscreen
  11572. this._onFullscreenChange = function () {
  11573. if (document.fullscreen !== undefined) {
  11574. _this.isFullscreen = document.fullscreen;
  11575. }
  11576. else if (document.mozFullScreen !== undefined) {
  11577. _this.isFullscreen = document.mozFullScreen;
  11578. }
  11579. else if (document.webkitIsFullScreen !== undefined) {
  11580. _this.isFullscreen = document.webkitIsFullScreen;
  11581. }
  11582. else if (document.msIsFullScreen !== undefined) {
  11583. _this.isFullscreen = document.msIsFullScreen;
  11584. }
  11585. // Pointer lock
  11586. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11587. canvas.requestPointerLock = canvas.requestPointerLock ||
  11588. canvas.msRequestPointerLock ||
  11589. canvas.mozRequestPointerLock ||
  11590. canvas.webkitRequestPointerLock;
  11591. if (canvas.requestPointerLock) {
  11592. canvas.requestPointerLock();
  11593. }
  11594. }
  11595. };
  11596. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11597. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11598. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11599. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11600. // Pointer lock
  11601. this._onPointerLockChange = function () {
  11602. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11603. document.webkitPointerLockElement === canvas ||
  11604. document.msPointerLockElement === canvas ||
  11605. document.pointerLockElement === canvas);
  11606. };
  11607. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11608. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11609. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11610. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11611. this._onVRDisplayPointerRestricted = function () {
  11612. if (canvas) {
  11613. canvas.requestPointerLock();
  11614. }
  11615. };
  11616. this._onVRDisplayPointerUnrestricted = function () {
  11617. document.exitPointerLock();
  11618. };
  11619. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11620. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11621. }
  11622. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11623. Engine.audioEngine = new BABYLON.AudioEngine();
  11624. }
  11625. // Prepare buffer pointers
  11626. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11627. this._currentBufferPointers[i] = new BufferPointer();
  11628. }
  11629. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11630. // Load WebVR Devices
  11631. if (options.autoEnableWebVR) {
  11632. this.initWebVR();
  11633. }
  11634. // Detect if we are running on a faulty buggy OS.
  11635. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11636. // Detect if we are running on a faulty buggy desktop OS.
  11637. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11638. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11639. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11640. }
  11641. Object.defineProperty(Engine, "LastCreatedEngine", {
  11642. /**
  11643. * Gets the latest created engine
  11644. */
  11645. get: function () {
  11646. if (Engine.Instances.length === 0) {
  11647. return null;
  11648. }
  11649. return Engine.Instances[Engine.Instances.length - 1];
  11650. },
  11651. enumerable: true,
  11652. configurable: true
  11653. });
  11654. Object.defineProperty(Engine, "LastCreatedScene", {
  11655. /**
  11656. * Gets the latest created scene
  11657. */
  11658. get: function () {
  11659. var lastCreatedEngine = Engine.LastCreatedEngine;
  11660. if (!lastCreatedEngine) {
  11661. return null;
  11662. }
  11663. if (lastCreatedEngine.scenes.length === 0) {
  11664. return null;
  11665. }
  11666. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. /**
  11672. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11673. * @param flag defines which part of the materials must be marked as dirty
  11674. * @param predicate defines a predicate used to filter which materials should be affected
  11675. */
  11676. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11677. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11678. var engine = Engine.Instances[engineIndex];
  11679. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11680. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11681. }
  11682. }
  11683. };
  11684. Object.defineProperty(Engine, "Version", {
  11685. /**
  11686. * Returns the current version of the framework
  11687. */
  11688. get: function () {
  11689. return "3.3.0-alpha.12";
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11695. /**
  11696. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11697. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11698. */
  11699. get: function () {
  11700. return this._vrExclusivePointerMode;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11706. /**
  11707. * Gets a boolean indicating that the engine supports uniform buffers
  11708. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11709. */
  11710. get: function () {
  11711. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11717. /**
  11718. * Gets a boolean indicating that only power of 2 textures are supported
  11719. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11720. */
  11721. get: function () {
  11722. return this._webGLVersion < 2 || this.forcePOTTextures;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11728. /**
  11729. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11730. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11731. */
  11732. get: function () {
  11733. return this._doNotHandleContextLost;
  11734. },
  11735. set: function (value) {
  11736. this._doNotHandleContextLost = value;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11742. /**
  11743. * Gets the performance monitor attached to this engine
  11744. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11745. */
  11746. get: function () {
  11747. return this._performanceMonitor;
  11748. },
  11749. enumerable: true,
  11750. configurable: true
  11751. });
  11752. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11753. /**
  11754. * Gets the list of texture formats supported
  11755. */
  11756. get: function () {
  11757. return this._texturesSupported;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11763. /**
  11764. * Gets the list of texture formats in use
  11765. */
  11766. get: function () {
  11767. return this._textureFormatInUse;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(Engine.prototype, "currentViewport", {
  11773. /**
  11774. * Gets the current viewport
  11775. */
  11776. get: function () {
  11777. return this._cachedViewport;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11783. /**
  11784. * Gets the default empty texture
  11785. */
  11786. get: function () {
  11787. if (!this._emptyTexture) {
  11788. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11789. }
  11790. return this._emptyTexture;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11796. /**
  11797. * Gets the default empty 3D texture
  11798. */
  11799. get: function () {
  11800. if (!this._emptyTexture3D) {
  11801. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11802. }
  11803. return this._emptyTexture3D;
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11809. /**
  11810. * Gets the default empty cube texture
  11811. */
  11812. get: function () {
  11813. if (!this._emptyCubeTexture) {
  11814. var faceData = new Uint8Array(4);
  11815. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11816. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11817. }
  11818. return this._emptyCubeTexture;
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. Engine.prototype._rebuildInternalTextures = function () {
  11824. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11825. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11826. var internalTexture = currentState_1[_i];
  11827. internalTexture._rebuild();
  11828. }
  11829. };
  11830. Engine.prototype._rebuildEffects = function () {
  11831. for (var key in this._compiledEffects) {
  11832. var effect = this._compiledEffects[key];
  11833. effect._prepareEffect();
  11834. }
  11835. BABYLON.Effect.ResetCache();
  11836. };
  11837. Engine.prototype._rebuildBuffers = function () {
  11838. // Index / Vertex
  11839. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11840. var scene = _a[_i];
  11841. scene.resetCachedMaterial();
  11842. scene._rebuildGeometries();
  11843. scene._rebuildTextures();
  11844. }
  11845. // Uniforms
  11846. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11847. var uniformBuffer = _c[_b];
  11848. uniformBuffer._rebuild();
  11849. }
  11850. };
  11851. Engine.prototype._initGLContext = function () {
  11852. // Caps
  11853. this._caps = new EngineCapabilities();
  11854. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11855. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11856. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11857. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11858. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11859. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11860. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11861. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11862. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11863. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11864. // Infos
  11865. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11866. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11867. if (rendererInfo != null) {
  11868. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11869. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11870. }
  11871. if (!this._glVendor) {
  11872. this._glVendor = "Unknown vendor";
  11873. }
  11874. if (!this._glRenderer) {
  11875. this._glRenderer = "Unknown renderer";
  11876. }
  11877. // Constants
  11878. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11879. if (this._gl.RGBA16F !== 0x881A) {
  11880. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11881. }
  11882. if (this._gl.RGBA32F !== 0x8814) {
  11883. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11884. }
  11885. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11886. this._gl.DEPTH24_STENCIL8 = 35056;
  11887. }
  11888. // Extensions
  11889. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11890. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11891. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11892. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11893. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11894. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11895. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11896. 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');
  11897. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11898. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11899. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11900. this._caps.highPrecisionShaderSupported = true;
  11901. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11902. if (this._caps.timerQuery) {
  11903. if (this._webGLVersion === 1) {
  11904. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11905. }
  11906. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11907. }
  11908. // Checks if some of the format renders first to allow the use of webgl inspector.
  11909. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11910. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11911. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11912. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11913. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11914. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11915. if (this._webGLVersion > 1) {
  11916. this._gl.HALF_FLOAT_OES = 0x140B;
  11917. }
  11918. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11919. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11920. // Draw buffers
  11921. if (this._webGLVersion > 1) {
  11922. this._caps.drawBuffersExtension = true;
  11923. }
  11924. else {
  11925. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11926. if (drawBuffersExtension !== null) {
  11927. this._caps.drawBuffersExtension = true;
  11928. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11929. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11930. for (var i = 0; i < 16; i++) {
  11931. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11932. }
  11933. }
  11934. else {
  11935. this._caps.drawBuffersExtension = false;
  11936. }
  11937. }
  11938. // Depth Texture
  11939. if (this._webGLVersion > 1) {
  11940. this._caps.depthTextureExtension = true;
  11941. }
  11942. else {
  11943. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11944. if (depthTextureExtension != null) {
  11945. this._caps.depthTextureExtension = true;
  11946. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11947. }
  11948. }
  11949. // Vertex array object
  11950. if (this._webGLVersion > 1) {
  11951. this._caps.vertexArrayObject = true;
  11952. }
  11953. else {
  11954. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11955. if (vertexArrayObjectExtension != null) {
  11956. this._caps.vertexArrayObject = true;
  11957. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11958. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11959. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11960. }
  11961. else {
  11962. this._caps.vertexArrayObject = false;
  11963. }
  11964. }
  11965. // Instances count
  11966. if (this._webGLVersion > 1) {
  11967. this._caps.instancedArrays = true;
  11968. }
  11969. else {
  11970. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11971. if (instanceExtension != null) {
  11972. this._caps.instancedArrays = true;
  11973. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11974. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11975. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11976. }
  11977. else {
  11978. this._caps.instancedArrays = false;
  11979. }
  11980. }
  11981. // Intelligently add supported compressed formats in order to check for.
  11982. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11983. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11984. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11985. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11986. if (this._caps.astc)
  11987. this.texturesSupported.push('-astc.ktx');
  11988. if (this._caps.s3tc)
  11989. this.texturesSupported.push('-dxt.ktx');
  11990. if (this._caps.pvrtc)
  11991. this.texturesSupported.push('-pvrtc.ktx');
  11992. if (this._caps.etc2)
  11993. this.texturesSupported.push('-etc2.ktx');
  11994. if (this._caps.etc1)
  11995. this.texturesSupported.push('-etc1.ktx');
  11996. if (this._gl.getShaderPrecisionFormat) {
  11997. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11998. if (highp) {
  11999. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12000. }
  12001. }
  12002. // Depth buffer
  12003. this.setDepthBuffer(true);
  12004. this.setDepthFunctionToLessOrEqual();
  12005. this.setDepthWrite(true);
  12006. // Texture maps
  12007. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12008. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12009. this._nextFreeTextureSlots.push(slot);
  12010. }
  12011. };
  12012. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12013. /**
  12014. * Gets version of the current webGL context
  12015. */
  12016. get: function () {
  12017. return this._webGLVersion;
  12018. },
  12019. enumerable: true,
  12020. configurable: true
  12021. });
  12022. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12023. /**
  12024. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12025. */
  12026. get: function () {
  12027. return this._isStencilEnable;
  12028. },
  12029. enumerable: true,
  12030. configurable: true
  12031. });
  12032. Engine.prototype._prepareWorkingCanvas = function () {
  12033. if (this._workingCanvas) {
  12034. return;
  12035. }
  12036. this._workingCanvas = document.createElement("canvas");
  12037. var context = this._workingCanvas.getContext("2d");
  12038. if (context) {
  12039. this._workingContext = context;
  12040. }
  12041. };
  12042. /**
  12043. * Reset the texture cache to empty state
  12044. */
  12045. Engine.prototype.resetTextureCache = function () {
  12046. for (var key in this._boundTexturesCache) {
  12047. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12048. continue;
  12049. }
  12050. var boundTexture = this._boundTexturesCache[key];
  12051. if (boundTexture) {
  12052. this._removeDesignatedSlot(boundTexture);
  12053. }
  12054. this._boundTexturesCache[key] = null;
  12055. }
  12056. if (!this.disableTextureBindingOptimization) {
  12057. this._nextFreeTextureSlots = [];
  12058. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12059. this._nextFreeTextureSlots.push(slot);
  12060. }
  12061. }
  12062. this._currentTextureChannel = -1;
  12063. };
  12064. /**
  12065. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12066. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12067. * @returns true if engine is in deterministic lock step mode
  12068. */
  12069. Engine.prototype.isDeterministicLockStep = function () {
  12070. return this._deterministicLockstep;
  12071. };
  12072. /**
  12073. * Gets the max steps when engine is running in deterministic lock step
  12074. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12075. * @returns the max steps
  12076. */
  12077. Engine.prototype.getLockstepMaxSteps = function () {
  12078. return this._lockstepMaxSteps;
  12079. };
  12080. /**
  12081. * Gets an object containing information about the current webGL context
  12082. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12083. */
  12084. Engine.prototype.getGlInfo = function () {
  12085. return {
  12086. vendor: this._glVendor,
  12087. renderer: this._glRenderer,
  12088. version: this._glVersion
  12089. };
  12090. };
  12091. /**
  12092. * Gets current aspect ratio
  12093. * @param camera defines the camera to use to get the aspect ratio
  12094. * @param useScreen defines if screen size must be used (or the current render target if any)
  12095. * @returns a number defining the aspect ratio
  12096. */
  12097. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12098. if (useScreen === void 0) { useScreen = false; }
  12099. var viewport = camera.viewport;
  12100. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12101. };
  12102. /**
  12103. * Gets current screen aspect ratio
  12104. * @returns a number defining the aspect ratio
  12105. */
  12106. Engine.prototype.getScreenAspectRatio = function () {
  12107. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12108. };
  12109. /**
  12110. * Gets the current render width
  12111. * @param useScreen defines if screen size must be used (or the current render target if any)
  12112. * @returns a number defining the current render width
  12113. */
  12114. Engine.prototype.getRenderWidth = function (useScreen) {
  12115. if (useScreen === void 0) { useScreen = false; }
  12116. if (!useScreen && this._currentRenderTarget) {
  12117. return this._currentRenderTarget.width;
  12118. }
  12119. return this._gl.drawingBufferWidth;
  12120. };
  12121. /**
  12122. * Gets the current render height
  12123. * @param useScreen defines if screen size must be used (or the current render target if any)
  12124. * @returns a number defining the current render height
  12125. */
  12126. Engine.prototype.getRenderHeight = function (useScreen) {
  12127. if (useScreen === void 0) { useScreen = false; }
  12128. if (!useScreen && this._currentRenderTarget) {
  12129. return this._currentRenderTarget.height;
  12130. }
  12131. return this._gl.drawingBufferHeight;
  12132. };
  12133. /**
  12134. * Gets the HTML canvas attached with the current webGL context
  12135. * @returns a HTML canvas
  12136. */
  12137. Engine.prototype.getRenderingCanvas = function () {
  12138. return this._renderingCanvas;
  12139. };
  12140. /**
  12141. * Gets the client rect of the HTML canvas attached with the current webGL context
  12142. * @returns a client rectanglee
  12143. */
  12144. Engine.prototype.getRenderingCanvasClientRect = function () {
  12145. if (!this._renderingCanvas) {
  12146. return null;
  12147. }
  12148. return this._renderingCanvas.getBoundingClientRect();
  12149. };
  12150. /**
  12151. * Defines the hardware scaling level.
  12152. * By default the hardware scaling level is computed from the window device ratio.
  12153. * 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.
  12154. * @param level defines the level to use
  12155. */
  12156. Engine.prototype.setHardwareScalingLevel = function (level) {
  12157. this._hardwareScalingLevel = level;
  12158. this.resize();
  12159. };
  12160. /**
  12161. * Gets the current hardware scaling level.
  12162. * By default the hardware scaling level is computed from the window device ratio.
  12163. * 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.
  12164. * @returns a number indicating the current hardware scaling level
  12165. */
  12166. Engine.prototype.getHardwareScalingLevel = function () {
  12167. return this._hardwareScalingLevel;
  12168. };
  12169. /**
  12170. * Gets the list of loaded textures
  12171. * @returns an array containing all loaded textures
  12172. */
  12173. Engine.prototype.getLoadedTexturesCache = function () {
  12174. return this._internalTexturesCache;
  12175. };
  12176. /**
  12177. * Gets the object containing all engine capabilities
  12178. * @returns the EngineCapabilities object
  12179. */
  12180. Engine.prototype.getCaps = function () {
  12181. return this._caps;
  12182. };
  12183. Object.defineProperty(Engine.prototype, "drawCalls", {
  12184. /** @hidden */
  12185. get: function () {
  12186. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12187. return 0;
  12188. },
  12189. enumerable: true,
  12190. configurable: true
  12191. });
  12192. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12193. /** @hidden */
  12194. get: function () {
  12195. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12196. return null;
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. /**
  12202. * Gets the current depth function
  12203. * @returns a number defining the depth function
  12204. */
  12205. Engine.prototype.getDepthFunction = function () {
  12206. return this._depthCullingState.depthFunc;
  12207. };
  12208. /**
  12209. * Sets the current depth function
  12210. * @param depthFunc defines the function to use
  12211. */
  12212. Engine.prototype.setDepthFunction = function (depthFunc) {
  12213. this._depthCullingState.depthFunc = depthFunc;
  12214. };
  12215. /**
  12216. * Sets the current depth function to GREATER
  12217. */
  12218. Engine.prototype.setDepthFunctionToGreater = function () {
  12219. this._depthCullingState.depthFunc = this._gl.GREATER;
  12220. };
  12221. /**
  12222. * Sets the current depth function to GEQUAL
  12223. */
  12224. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12225. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12226. };
  12227. /**
  12228. * Sets the current depth function to LESS
  12229. */
  12230. Engine.prototype.setDepthFunctionToLess = function () {
  12231. this._depthCullingState.depthFunc = this._gl.LESS;
  12232. };
  12233. /**
  12234. * Sets the current depth function to LEQUAL
  12235. */
  12236. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12237. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12238. };
  12239. /**
  12240. * Gets a boolean indicating if stencil buffer is enabled
  12241. * @returns the current stencil buffer state
  12242. */
  12243. Engine.prototype.getStencilBuffer = function () {
  12244. return this._stencilState.stencilTest;
  12245. };
  12246. /**
  12247. * Enable or disable the stencil buffer
  12248. * @param enable defines if the stencil buffer must be enabled or disabled
  12249. */
  12250. Engine.prototype.setStencilBuffer = function (enable) {
  12251. this._stencilState.stencilTest = enable;
  12252. };
  12253. /**
  12254. * Gets the current stencil mask
  12255. * @returns a number defining the new stencil mask to use
  12256. */
  12257. Engine.prototype.getStencilMask = function () {
  12258. return this._stencilState.stencilMask;
  12259. };
  12260. /**
  12261. * Sets the current stencil mask
  12262. * @param mask defines the new stencil mask to use
  12263. */
  12264. Engine.prototype.setStencilMask = function (mask) {
  12265. this._stencilState.stencilMask = mask;
  12266. };
  12267. /**
  12268. * Gets the current stencil function
  12269. * @returns a number defining the stencil function to use
  12270. */
  12271. Engine.prototype.getStencilFunction = function () {
  12272. return this._stencilState.stencilFunc;
  12273. };
  12274. /**
  12275. * Gets the current stencil reference value
  12276. * @returns a number defining the stencil reference value to use
  12277. */
  12278. Engine.prototype.getStencilFunctionReference = function () {
  12279. return this._stencilState.stencilFuncRef;
  12280. };
  12281. /**
  12282. * Gets the current stencil mask
  12283. * @returns a number defining the stencil mask to use
  12284. */
  12285. Engine.prototype.getStencilFunctionMask = function () {
  12286. return this._stencilState.stencilFuncMask;
  12287. };
  12288. /**
  12289. * Sets the current stencil function
  12290. * @param stencilFunc defines the new stencil function to use
  12291. */
  12292. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12293. this._stencilState.stencilFunc = stencilFunc;
  12294. };
  12295. /**
  12296. * Sets the current stencil reference
  12297. * @param reference defines the new stencil reference to use
  12298. */
  12299. Engine.prototype.setStencilFunctionReference = function (reference) {
  12300. this._stencilState.stencilFuncRef = reference;
  12301. };
  12302. /**
  12303. * Sets the current stencil mask
  12304. * @param mask defines the new stencil mask to use
  12305. */
  12306. Engine.prototype.setStencilFunctionMask = function (mask) {
  12307. this._stencilState.stencilFuncMask = mask;
  12308. };
  12309. /**
  12310. * Gets the current stencil operation when stencil fails
  12311. * @returns a number defining stencil operation to use when stencil fails
  12312. */
  12313. Engine.prototype.getStencilOperationFail = function () {
  12314. return this._stencilState.stencilOpStencilFail;
  12315. };
  12316. /**
  12317. * Gets the current stencil operation when depth fails
  12318. * @returns a number defining stencil operation to use when depth fails
  12319. */
  12320. Engine.prototype.getStencilOperationDepthFail = function () {
  12321. return this._stencilState.stencilOpDepthFail;
  12322. };
  12323. /**
  12324. * Gets the current stencil operation when stencil passes
  12325. * @returns a number defining stencil operation to use when stencil passes
  12326. */
  12327. Engine.prototype.getStencilOperationPass = function () {
  12328. return this._stencilState.stencilOpStencilDepthPass;
  12329. };
  12330. /**
  12331. * Sets the stencil operation to use when stencil fails
  12332. * @param operation defines the stencil operation to use when stencil fails
  12333. */
  12334. Engine.prototype.setStencilOperationFail = function (operation) {
  12335. this._stencilState.stencilOpStencilFail = operation;
  12336. };
  12337. /**
  12338. * Sets the stencil operation to use when depth fails
  12339. * @param operation defines the stencil operation to use when depth fails
  12340. */
  12341. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12342. this._stencilState.stencilOpDepthFail = operation;
  12343. };
  12344. /**
  12345. * Sets the stencil operation to use when stencil passes
  12346. * @param operation defines the stencil operation to use when stencil passes
  12347. */
  12348. Engine.prototype.setStencilOperationPass = function (operation) {
  12349. this._stencilState.stencilOpStencilDepthPass = operation;
  12350. };
  12351. /**
  12352. * Sets a boolean indicating if the dithering state is enabled or disabled
  12353. * @param value defines the dithering state
  12354. */
  12355. Engine.prototype.setDitheringState = function (value) {
  12356. if (value) {
  12357. this._gl.enable(this._gl.DITHER);
  12358. }
  12359. else {
  12360. this._gl.disable(this._gl.DITHER);
  12361. }
  12362. };
  12363. /**
  12364. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12365. * @param value defines the rasterizer state
  12366. */
  12367. Engine.prototype.setRasterizerState = function (value) {
  12368. if (value) {
  12369. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12370. }
  12371. else {
  12372. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12373. }
  12374. };
  12375. /**
  12376. * stop executing a render loop function and remove it from the execution array
  12377. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12378. */
  12379. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12380. if (!renderFunction) {
  12381. this._activeRenderLoops = [];
  12382. return;
  12383. }
  12384. var index = this._activeRenderLoops.indexOf(renderFunction);
  12385. if (index >= 0) {
  12386. this._activeRenderLoops.splice(index, 1);
  12387. }
  12388. };
  12389. /** @hidden */
  12390. Engine.prototype._renderLoop = function () {
  12391. if (!this._contextWasLost) {
  12392. var shouldRender = true;
  12393. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12394. shouldRender = false;
  12395. }
  12396. if (shouldRender) {
  12397. // Start new frame
  12398. this.beginFrame();
  12399. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12400. var renderFunction = this._activeRenderLoops[index];
  12401. renderFunction();
  12402. }
  12403. // Present
  12404. this.endFrame();
  12405. }
  12406. }
  12407. if (this._activeRenderLoops.length > 0) {
  12408. // Register new frame
  12409. var requester = null;
  12410. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12411. requester = this._vrDisplay;
  12412. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12413. }
  12414. else {
  12415. this._renderingQueueLaunched = false;
  12416. }
  12417. };
  12418. /**
  12419. * Register and execute a render loop. The engine can have more than one render function
  12420. * @param renderFunction defines the function to continuously execute
  12421. */
  12422. Engine.prototype.runRenderLoop = function (renderFunction) {
  12423. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12424. return;
  12425. }
  12426. this._activeRenderLoops.push(renderFunction);
  12427. if (!this._renderingQueueLaunched) {
  12428. this._renderingQueueLaunched = true;
  12429. this._bindedRenderFunction = this._renderLoop.bind(this);
  12430. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12431. }
  12432. };
  12433. /**
  12434. * Toggle full screen mode
  12435. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12436. * @param options defines an option object to be sent to the requestFullscreen function
  12437. */
  12438. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12439. if (this.isFullscreen) {
  12440. BABYLON.Tools.ExitFullscreen();
  12441. }
  12442. else {
  12443. this._pointerLockRequested = requestPointerLock;
  12444. if (this._renderingCanvas) {
  12445. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12446. }
  12447. }
  12448. };
  12449. /**
  12450. * Clear the current render buffer or the current render target (if any is set up)
  12451. * @param color defines the color to use
  12452. * @param backBuffer defines if the back buffer must be cleared
  12453. * @param depth defines if the depth buffer must be cleared
  12454. * @param stencil defines if the stencil buffer must be cleared
  12455. */
  12456. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12457. if (stencil === void 0) { stencil = false; }
  12458. this.applyStates();
  12459. var mode = 0;
  12460. if (backBuffer && color) {
  12461. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12462. mode |= this._gl.COLOR_BUFFER_BIT;
  12463. }
  12464. if (depth) {
  12465. this._gl.clearDepth(1.0);
  12466. mode |= this._gl.DEPTH_BUFFER_BIT;
  12467. }
  12468. if (stencil) {
  12469. this._gl.clearStencil(0);
  12470. mode |= this._gl.STENCIL_BUFFER_BIT;
  12471. }
  12472. this._gl.clear(mode);
  12473. };
  12474. /**
  12475. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12476. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12477. * @param y defines the y-coordinate of the corner of the clear rectangle
  12478. * @param width defines the width of the clear rectangle
  12479. * @param height defines the height of the clear rectangle
  12480. * @param clearColor defines the clear color
  12481. */
  12482. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12483. var gl = this._gl;
  12484. // Save state
  12485. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12486. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12487. // Change state
  12488. gl.enable(gl.SCISSOR_TEST);
  12489. gl.scissor(x, y, width, height);
  12490. // Clear
  12491. this.clear(clearColor, true, true, true);
  12492. // Restore state
  12493. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12494. if (curScissor === true) {
  12495. gl.enable(gl.SCISSOR_TEST);
  12496. }
  12497. else {
  12498. gl.disable(gl.SCISSOR_TEST);
  12499. }
  12500. };
  12501. /** @hidden */
  12502. Engine.prototype._viewport = function (x, y, width, height) {
  12503. if (x !== this._viewportCached.x ||
  12504. y !== this._viewportCached.y ||
  12505. width !== this._viewportCached.z ||
  12506. height !== this._viewportCached.w) {
  12507. this._viewportCached.x = x;
  12508. this._viewportCached.y = y;
  12509. this._viewportCached.z = width;
  12510. this._viewportCached.w = height;
  12511. this._gl.viewport(x, y, width, height);
  12512. }
  12513. };
  12514. /**
  12515. * Set the WebGL's viewport
  12516. * @param viewport defines the viewport element to be used
  12517. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12518. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12519. */
  12520. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12521. var width = requiredWidth || this.getRenderWidth();
  12522. var height = requiredHeight || this.getRenderHeight();
  12523. var x = viewport.x || 0;
  12524. var y = viewport.y || 0;
  12525. this._cachedViewport = viewport;
  12526. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12527. };
  12528. /**
  12529. * Directly set the WebGL Viewport
  12530. * @param x defines the x coordinate of the viewport (in screen space)
  12531. * @param y defines the y coordinate of the viewport (in screen space)
  12532. * @param width defines the width of the viewport (in screen space)
  12533. * @param height defines the height of the viewport (in screen space)
  12534. * @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
  12535. */
  12536. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12537. var currentViewport = this._cachedViewport;
  12538. this._cachedViewport = null;
  12539. this._viewport(x, y, width, height);
  12540. return currentViewport;
  12541. };
  12542. /**
  12543. * Begin a new frame
  12544. */
  12545. Engine.prototype.beginFrame = function () {
  12546. this.onBeginFrameObservable.notifyObservers(this);
  12547. this._measureFps();
  12548. };
  12549. /**
  12550. * Enf the current frame
  12551. */
  12552. Engine.prototype.endFrame = function () {
  12553. // Force a flush in case we are using a bad OS.
  12554. if (this._badOS) {
  12555. this.flushFramebuffer();
  12556. }
  12557. // Submit frame to the vr device, if enabled
  12558. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12559. // TODO: We should only submit the frame if we read frameData successfully.
  12560. this._vrDisplay.submitFrame();
  12561. }
  12562. this.onEndFrameObservable.notifyObservers(this);
  12563. };
  12564. /**
  12565. * Resize the view according to the canvas' size
  12566. */
  12567. Engine.prototype.resize = function () {
  12568. // We're not resizing the size of the canvas while in VR mode & presenting
  12569. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12570. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12571. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12572. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12573. }
  12574. };
  12575. /**
  12576. * Force a specific size of the canvas
  12577. * @param width defines the new canvas' width
  12578. * @param height defines the new canvas' height
  12579. */
  12580. Engine.prototype.setSize = function (width, height) {
  12581. if (!this._renderingCanvas) {
  12582. return;
  12583. }
  12584. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12585. return;
  12586. }
  12587. this._renderingCanvas.width = width;
  12588. this._renderingCanvas.height = height;
  12589. for (var index = 0; index < this.scenes.length; index++) {
  12590. var scene = this.scenes[index];
  12591. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12592. var cam = scene.cameras[camIndex];
  12593. cam._currentRenderId = 0;
  12594. }
  12595. }
  12596. if (this.onResizeObservable.hasObservers) {
  12597. this.onResizeObservable.notifyObservers(this);
  12598. }
  12599. };
  12600. // WebVR functions
  12601. /**
  12602. * Gets a boolean indicating if a webVR device was detected
  12603. * @returns true if a webVR device was detected
  12604. */
  12605. Engine.prototype.isVRDevicePresent = function () {
  12606. return !!this._vrDisplay;
  12607. };
  12608. /**
  12609. * Gets the current webVR device
  12610. * @returns the current webVR device (or null)
  12611. */
  12612. Engine.prototype.getVRDevice = function () {
  12613. return this._vrDisplay;
  12614. };
  12615. /**
  12616. * Initializes a webVR display and starts listening to display change events
  12617. * The onVRDisplayChangedObservable will be notified upon these changes
  12618. * @returns The onVRDisplayChangedObservable
  12619. */
  12620. Engine.prototype.initWebVR = function () {
  12621. this.initWebVRAsync();
  12622. return this.onVRDisplayChangedObservable;
  12623. };
  12624. /**
  12625. * Initializes a webVR display and starts listening to display change events
  12626. * The onVRDisplayChangedObservable will be notified upon these changes
  12627. * @returns A promise containing a VRDisplay and if vr is supported
  12628. */
  12629. Engine.prototype.initWebVRAsync = function () {
  12630. var _this = this;
  12631. var notifyObservers = function () {
  12632. var eventArgs = {
  12633. vrDisplay: _this._vrDisplay,
  12634. vrSupported: _this._vrSupported
  12635. };
  12636. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12637. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12638. };
  12639. if (!this._onVrDisplayConnect) {
  12640. this._onVrDisplayConnect = function (event) {
  12641. _this._vrDisplay = event.display;
  12642. notifyObservers();
  12643. };
  12644. this._onVrDisplayDisconnect = function () {
  12645. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12646. _this._vrDisplay = undefined;
  12647. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12648. notifyObservers();
  12649. };
  12650. this._onVrDisplayPresentChange = function () {
  12651. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12652. };
  12653. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12654. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12655. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12656. }
  12657. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12658. this._webVRInitPromise.then(notifyObservers);
  12659. return this._webVRInitPromise;
  12660. };
  12661. /**
  12662. * Call this function to switch to webVR mode
  12663. * Will do nothing if webVR is not supported or if there is no webVR device
  12664. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12665. */
  12666. Engine.prototype.enableVR = function () {
  12667. var _this = this;
  12668. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12669. var onResolved = function () {
  12670. _this.onVRRequestPresentComplete.notifyObservers(true);
  12671. _this._onVRFullScreenTriggered();
  12672. };
  12673. var onRejected = function () {
  12674. _this.onVRRequestPresentComplete.notifyObservers(false);
  12675. };
  12676. this.onVRRequestPresentStart.notifyObservers(this);
  12677. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12678. }
  12679. };
  12680. /**
  12681. * Call this function to leave webVR mode
  12682. * Will do nothing if webVR is not supported or if there is no webVR device
  12683. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12684. */
  12685. Engine.prototype.disableVR = function () {
  12686. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12687. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12688. }
  12689. };
  12690. Engine.prototype._getVRDisplaysAsync = function () {
  12691. var _this = this;
  12692. return new Promise(function (res, rej) {
  12693. if (navigator.getVRDisplays) {
  12694. navigator.getVRDisplays().then(function (devices) {
  12695. _this._vrSupported = true;
  12696. // note that devices may actually be an empty array. This is fine;
  12697. // we expect this._vrDisplay to be undefined in this case.
  12698. _this._vrDisplay = devices[0];
  12699. res({
  12700. vrDisplay: _this._vrDisplay,
  12701. vrSupported: _this._vrSupported
  12702. });
  12703. });
  12704. }
  12705. else {
  12706. _this._vrDisplay = undefined;
  12707. _this._vrSupported = false;
  12708. res({
  12709. vrDisplay: _this._vrDisplay,
  12710. vrSupported: _this._vrSupported
  12711. });
  12712. }
  12713. });
  12714. };
  12715. /**
  12716. * Binds the frame buffer to the specified texture.
  12717. * @param texture The texture to render to or null for the default canvas
  12718. * @param faceIndex The face of the texture to render to in case of cube texture
  12719. * @param requiredWidth The width of the target to render to
  12720. * @param requiredHeight The height of the target to render to
  12721. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12722. * @param depthStencilTexture The depth stencil texture to use to render
  12723. * @param lodLevel defines le lod level to bind to the frame buffer
  12724. */
  12725. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12726. if (lodLevel === void 0) { lodLevel = 0; }
  12727. if (this._currentRenderTarget) {
  12728. this.unBindFramebuffer(this._currentRenderTarget);
  12729. }
  12730. this._currentRenderTarget = texture;
  12731. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12732. var gl = this._gl;
  12733. if (texture.isCube) {
  12734. if (faceIndex === undefined) {
  12735. faceIndex = 0;
  12736. }
  12737. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12738. if (depthStencilTexture) {
  12739. if (depthStencilTexture._generateStencilBuffer) {
  12740. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12741. }
  12742. else {
  12743. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12744. }
  12745. }
  12746. }
  12747. if (this._cachedViewport && !forceFullscreenViewport) {
  12748. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12749. }
  12750. else {
  12751. if (!requiredWidth) {
  12752. requiredWidth = texture.width;
  12753. if (lodLevel) {
  12754. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12755. }
  12756. }
  12757. if (!requiredHeight) {
  12758. requiredHeight = texture.height;
  12759. if (lodLevel) {
  12760. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12761. }
  12762. }
  12763. this._viewport(0, 0, requiredWidth, requiredHeight);
  12764. }
  12765. this.wipeCaches();
  12766. };
  12767. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12768. if (this._currentFramebuffer !== framebuffer) {
  12769. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12770. this._currentFramebuffer = framebuffer;
  12771. }
  12772. };
  12773. /**
  12774. * Unbind the current render target texture from the webGL context
  12775. * @param texture defines the render target texture to unbind
  12776. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12777. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12778. */
  12779. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12780. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12781. this._currentRenderTarget = null;
  12782. // If MSAA, we need to bitblt back to main texture
  12783. var gl = this._gl;
  12784. if (texture._MSAAFramebuffer) {
  12785. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12786. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12787. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12788. }
  12789. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12790. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12791. gl.generateMipmap(gl.TEXTURE_2D);
  12792. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12793. }
  12794. if (onBeforeUnbind) {
  12795. if (texture._MSAAFramebuffer) {
  12796. // Bind the correct framebuffer
  12797. this.bindUnboundFramebuffer(texture._framebuffer);
  12798. }
  12799. onBeforeUnbind();
  12800. }
  12801. this.bindUnboundFramebuffer(null);
  12802. };
  12803. /**
  12804. * Unbind a list of render target textures from the webGL context
  12805. * This is used only when drawBuffer extension or webGL2 are active
  12806. * @param textures defines the render target textures to unbind
  12807. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12808. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12809. */
  12810. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12811. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12812. this._currentRenderTarget = null;
  12813. // If MSAA, we need to bitblt back to main texture
  12814. var gl = this._gl;
  12815. if (textures[0]._MSAAFramebuffer) {
  12816. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12817. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12818. var attachments = textures[0]._attachments;
  12819. if (!attachments) {
  12820. attachments = new Array(textures.length);
  12821. textures[0]._attachments = attachments;
  12822. }
  12823. for (var i = 0; i < textures.length; i++) {
  12824. var texture = textures[i];
  12825. for (var j = 0; j < attachments.length; j++) {
  12826. attachments[j] = gl.NONE;
  12827. }
  12828. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12829. gl.readBuffer(attachments[i]);
  12830. gl.drawBuffers(attachments);
  12831. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12832. }
  12833. for (var i = 0; i < attachments.length; i++) {
  12834. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12835. }
  12836. gl.drawBuffers(attachments);
  12837. }
  12838. for (var i = 0; i < textures.length; i++) {
  12839. var texture = textures[i];
  12840. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12841. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12842. gl.generateMipmap(gl.TEXTURE_2D);
  12843. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12844. }
  12845. }
  12846. if (onBeforeUnbind) {
  12847. if (textures[0]._MSAAFramebuffer) {
  12848. // Bind the correct framebuffer
  12849. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12850. }
  12851. onBeforeUnbind();
  12852. }
  12853. this.bindUnboundFramebuffer(null);
  12854. };
  12855. /**
  12856. * Force the mipmap generation for the given render target texture
  12857. * @param texture defines the render target texture to use
  12858. */
  12859. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12860. if (texture.generateMipMaps) {
  12861. var gl = this._gl;
  12862. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12863. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12864. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12865. }
  12866. };
  12867. /**
  12868. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12869. */
  12870. Engine.prototype.flushFramebuffer = function () {
  12871. this._gl.flush();
  12872. };
  12873. /**
  12874. * Unbind the current render target and bind the default framebuffer
  12875. */
  12876. Engine.prototype.restoreDefaultFramebuffer = function () {
  12877. if (this._currentRenderTarget) {
  12878. this.unBindFramebuffer(this._currentRenderTarget);
  12879. }
  12880. else {
  12881. this.bindUnboundFramebuffer(null);
  12882. }
  12883. if (this._cachedViewport) {
  12884. this.setViewport(this._cachedViewport);
  12885. }
  12886. this.wipeCaches();
  12887. };
  12888. // UBOs
  12889. /**
  12890. * Create an uniform buffer
  12891. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12892. * @param elements defines the content of the uniform buffer
  12893. * @returns the webGL uniform buffer
  12894. */
  12895. Engine.prototype.createUniformBuffer = function (elements) {
  12896. var ubo = this._gl.createBuffer();
  12897. if (!ubo) {
  12898. throw new Error("Unable to create uniform buffer");
  12899. }
  12900. this.bindUniformBuffer(ubo);
  12901. if (elements instanceof Float32Array) {
  12902. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12903. }
  12904. else {
  12905. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12906. }
  12907. this.bindUniformBuffer(null);
  12908. ubo.references = 1;
  12909. return ubo;
  12910. };
  12911. /**
  12912. * Create a dynamic uniform buffer
  12913. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12914. * @param elements defines the content of the uniform buffer
  12915. * @returns the webGL uniform buffer
  12916. */
  12917. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12918. var ubo = this._gl.createBuffer();
  12919. if (!ubo) {
  12920. throw new Error("Unable to create dynamic uniform buffer");
  12921. }
  12922. this.bindUniformBuffer(ubo);
  12923. if (elements instanceof Float32Array) {
  12924. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12925. }
  12926. else {
  12927. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12928. }
  12929. this.bindUniformBuffer(null);
  12930. ubo.references = 1;
  12931. return ubo;
  12932. };
  12933. /**
  12934. * Update an existing uniform buffer
  12935. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12936. * @param uniformBuffer defines the target uniform buffer
  12937. * @param elements defines the content to update
  12938. * @param offset defines the offset in the uniform buffer where update should start
  12939. * @param count defines the size of the data to update
  12940. */
  12941. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12942. this.bindUniformBuffer(uniformBuffer);
  12943. if (offset === undefined) {
  12944. offset = 0;
  12945. }
  12946. if (count === undefined) {
  12947. if (elements instanceof Float32Array) {
  12948. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12949. }
  12950. else {
  12951. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12952. }
  12953. }
  12954. else {
  12955. if (elements instanceof Float32Array) {
  12956. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12957. }
  12958. else {
  12959. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12960. }
  12961. }
  12962. this.bindUniformBuffer(null);
  12963. };
  12964. // VBOs
  12965. Engine.prototype._resetVertexBufferBinding = function () {
  12966. this.bindArrayBuffer(null);
  12967. this._cachedVertexBuffers = null;
  12968. };
  12969. /**
  12970. * Creates a vertex buffer
  12971. * @param data the data for the vertex buffer
  12972. * @returns the new WebGL static buffer
  12973. */
  12974. Engine.prototype.createVertexBuffer = function (data) {
  12975. var vbo = this._gl.createBuffer();
  12976. if (!vbo) {
  12977. throw new Error("Unable to create vertex buffer");
  12978. }
  12979. this.bindArrayBuffer(vbo);
  12980. if (data instanceof Array) {
  12981. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12982. }
  12983. else {
  12984. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12985. }
  12986. this._resetVertexBufferBinding();
  12987. vbo.references = 1;
  12988. return vbo;
  12989. };
  12990. /**
  12991. * Creates a dynamic vertex buffer
  12992. * @param data the data for the dynamic vertex buffer
  12993. * @returns the new WebGL dynamic buffer
  12994. */
  12995. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12996. var vbo = this._gl.createBuffer();
  12997. if (!vbo) {
  12998. throw new Error("Unable to create dynamic vertex buffer");
  12999. }
  13000. this.bindArrayBuffer(vbo);
  13001. if (data instanceof Array) {
  13002. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13003. }
  13004. else {
  13005. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13006. }
  13007. this._resetVertexBufferBinding();
  13008. vbo.references = 1;
  13009. return vbo;
  13010. };
  13011. /**
  13012. * Update a dynamic index buffer
  13013. * @param indexBuffer defines the target index buffer
  13014. * @param indices defines the data to update
  13015. * @param offset defines the offset in the target index buffer where update should start
  13016. */
  13017. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13018. if (offset === void 0) { offset = 0; }
  13019. // Force cache update
  13020. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13021. this.bindIndexBuffer(indexBuffer);
  13022. var arrayBuffer;
  13023. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13024. arrayBuffer = indices;
  13025. }
  13026. else {
  13027. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13028. }
  13029. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13030. this._resetIndexBufferBinding();
  13031. };
  13032. /**
  13033. * Updates a dynamic vertex buffer.
  13034. * @param vertexBuffer the vertex buffer to update
  13035. * @param data the data used to update the vertex buffer
  13036. * @param byteOffset the byte offset of the data
  13037. * @param byteLength the byte length of the data
  13038. */
  13039. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13040. this.bindArrayBuffer(vertexBuffer);
  13041. if (byteOffset === undefined) {
  13042. byteOffset = 0;
  13043. }
  13044. if (byteLength === undefined) {
  13045. if (data instanceof Array) {
  13046. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13047. }
  13048. else {
  13049. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13050. }
  13051. }
  13052. else {
  13053. if (data instanceof Array) {
  13054. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13055. }
  13056. else {
  13057. if (data instanceof ArrayBuffer) {
  13058. data = new Uint8Array(data, byteOffset, byteLength);
  13059. }
  13060. else {
  13061. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13062. }
  13063. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13064. }
  13065. }
  13066. this._resetVertexBufferBinding();
  13067. };
  13068. Engine.prototype._resetIndexBufferBinding = function () {
  13069. this.bindIndexBuffer(null);
  13070. this._cachedIndexBuffer = null;
  13071. };
  13072. /**
  13073. * Creates a new index buffer
  13074. * @param indices defines the content of the index buffer
  13075. * @param updatable defines if the index buffer must be updatable
  13076. * @returns a new webGL buffer
  13077. */
  13078. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13079. var vbo = this._gl.createBuffer();
  13080. if (!vbo) {
  13081. throw new Error("Unable to create index buffer");
  13082. }
  13083. this.bindIndexBuffer(vbo);
  13084. // Check for 32 bits indices
  13085. var arrayBuffer;
  13086. var need32Bits = false;
  13087. if (indices instanceof Uint16Array) {
  13088. arrayBuffer = indices;
  13089. }
  13090. else {
  13091. //check 32 bit support
  13092. if (this._caps.uintIndices) {
  13093. if (indices instanceof Uint32Array) {
  13094. arrayBuffer = indices;
  13095. need32Bits = true;
  13096. }
  13097. else {
  13098. //number[] or Int32Array, check if 32 bit is necessary
  13099. for (var index = 0; index < indices.length; index++) {
  13100. if (indices[index] > 65535) {
  13101. need32Bits = true;
  13102. break;
  13103. }
  13104. }
  13105. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13106. }
  13107. }
  13108. else {
  13109. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13110. arrayBuffer = new Uint16Array(indices);
  13111. }
  13112. }
  13113. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13114. this._resetIndexBufferBinding();
  13115. vbo.references = 1;
  13116. vbo.is32Bits = need32Bits;
  13117. return vbo;
  13118. };
  13119. /**
  13120. * Bind a webGL buffer to the webGL context
  13121. * @param buffer defines the buffer to bind
  13122. */
  13123. Engine.prototype.bindArrayBuffer = function (buffer) {
  13124. if (!this._vaoRecordInProgress) {
  13125. this._unbindVertexArrayObject();
  13126. }
  13127. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13128. };
  13129. /**
  13130. * Bind an uniform buffer to the current webGL context
  13131. * @param buffer defines the buffer to bind
  13132. */
  13133. Engine.prototype.bindUniformBuffer = function (buffer) {
  13134. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13135. };
  13136. /**
  13137. * Bind a buffer to the current webGL context at a given location
  13138. * @param buffer defines the buffer to bind
  13139. * @param location defines the index where to bind the buffer
  13140. */
  13141. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13142. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13143. };
  13144. /**
  13145. * Bind a specific block at a given index in a specific shader program
  13146. * @param shaderProgram defines the shader program
  13147. * @param blockName defines the block name
  13148. * @param index defines the index where to bind the block
  13149. */
  13150. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13151. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13152. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13153. };
  13154. ;
  13155. Engine.prototype.bindIndexBuffer = function (buffer) {
  13156. if (!this._vaoRecordInProgress) {
  13157. this._unbindVertexArrayObject();
  13158. }
  13159. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13160. };
  13161. Engine.prototype.bindBuffer = function (buffer, target) {
  13162. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13163. this._gl.bindBuffer(target, buffer);
  13164. this._currentBoundBuffer[target] = buffer;
  13165. }
  13166. };
  13167. /**
  13168. * update the bound buffer with the given data
  13169. * @param data defines the data to update
  13170. */
  13171. Engine.prototype.updateArrayBuffer = function (data) {
  13172. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13173. };
  13174. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13175. var pointer = this._currentBufferPointers[indx];
  13176. var changed = false;
  13177. if (!pointer.active) {
  13178. changed = true;
  13179. pointer.active = true;
  13180. pointer.index = indx;
  13181. pointer.size = size;
  13182. pointer.type = type;
  13183. pointer.normalized = normalized;
  13184. pointer.stride = stride;
  13185. pointer.offset = offset;
  13186. pointer.buffer = buffer;
  13187. }
  13188. else {
  13189. if (pointer.buffer !== buffer) {
  13190. pointer.buffer = buffer;
  13191. changed = true;
  13192. }
  13193. if (pointer.size !== size) {
  13194. pointer.size = size;
  13195. changed = true;
  13196. }
  13197. if (pointer.type !== type) {
  13198. pointer.type = type;
  13199. changed = true;
  13200. }
  13201. if (pointer.normalized !== normalized) {
  13202. pointer.normalized = normalized;
  13203. changed = true;
  13204. }
  13205. if (pointer.stride !== stride) {
  13206. pointer.stride = stride;
  13207. changed = true;
  13208. }
  13209. if (pointer.offset !== offset) {
  13210. pointer.offset = offset;
  13211. changed = true;
  13212. }
  13213. }
  13214. if (changed || this._vaoRecordInProgress) {
  13215. this.bindArrayBuffer(buffer);
  13216. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13217. }
  13218. };
  13219. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13220. if (indexBuffer == null) {
  13221. return;
  13222. }
  13223. if (this._cachedIndexBuffer !== indexBuffer) {
  13224. this._cachedIndexBuffer = indexBuffer;
  13225. this.bindIndexBuffer(indexBuffer);
  13226. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13227. }
  13228. };
  13229. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13230. var attributes = effect.getAttributesNames();
  13231. if (!this._vaoRecordInProgress) {
  13232. this._unbindVertexArrayObject();
  13233. }
  13234. this.unbindAllAttributes();
  13235. for (var index = 0; index < attributes.length; index++) {
  13236. var order = effect.getAttributeLocation(index);
  13237. if (order >= 0) {
  13238. var vertexBuffer = vertexBuffers[attributes[index]];
  13239. if (!vertexBuffer) {
  13240. continue;
  13241. }
  13242. this._gl.enableVertexAttribArray(order);
  13243. if (!this._vaoRecordInProgress) {
  13244. this._vertexAttribArraysEnabled[order] = true;
  13245. }
  13246. var buffer = vertexBuffer.getBuffer();
  13247. if (buffer) {
  13248. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13249. if (vertexBuffer.getIsInstanced()) {
  13250. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13251. if (!this._vaoRecordInProgress) {
  13252. this._currentInstanceLocations.push(order);
  13253. this._currentInstanceBuffers.push(buffer);
  13254. }
  13255. }
  13256. }
  13257. }
  13258. }
  13259. };
  13260. /**
  13261. * Records a vertex array object
  13262. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13263. * @param vertexBuffers defines the list of vertex buffers to store
  13264. * @param indexBuffer defines the index buffer to store
  13265. * @param effect defines the effect to store
  13266. * @returns the new vertex array object
  13267. */
  13268. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13269. var vao = this._gl.createVertexArray();
  13270. this._vaoRecordInProgress = true;
  13271. this._gl.bindVertexArray(vao);
  13272. this._mustWipeVertexAttributes = true;
  13273. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13274. this.bindIndexBuffer(indexBuffer);
  13275. this._vaoRecordInProgress = false;
  13276. this._gl.bindVertexArray(null);
  13277. return vao;
  13278. };
  13279. /**
  13280. * Bind a specific vertex array object
  13281. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13282. * @param vertexArrayObject defines the vertex array object to bind
  13283. * @param indexBuffer defines the index buffer to bind
  13284. */
  13285. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13286. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13287. this._cachedVertexArrayObject = vertexArrayObject;
  13288. this._gl.bindVertexArray(vertexArrayObject);
  13289. this._cachedVertexBuffers = null;
  13290. this._cachedIndexBuffer = null;
  13291. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13292. this._mustWipeVertexAttributes = true;
  13293. }
  13294. };
  13295. /**
  13296. * Bind webGl buffers directly to the webGL context
  13297. * @param vertexBuffer defines the vertex buffer to bind
  13298. * @param indexBuffer defines the index buffer to bind
  13299. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13300. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13301. * @param effect defines the effect associated with the vertex buffer
  13302. */
  13303. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13304. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13305. this._cachedVertexBuffers = vertexBuffer;
  13306. this._cachedEffectForVertexBuffers = effect;
  13307. var attributesCount = effect.getAttributesCount();
  13308. this._unbindVertexArrayObject();
  13309. this.unbindAllAttributes();
  13310. var offset = 0;
  13311. for (var index = 0; index < attributesCount; index++) {
  13312. if (index < vertexDeclaration.length) {
  13313. var order = effect.getAttributeLocation(index);
  13314. if (order >= 0) {
  13315. this._gl.enableVertexAttribArray(order);
  13316. this._vertexAttribArraysEnabled[order] = true;
  13317. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13318. }
  13319. offset += vertexDeclaration[index] * 4;
  13320. }
  13321. }
  13322. }
  13323. this._bindIndexBufferWithCache(indexBuffer);
  13324. };
  13325. Engine.prototype._unbindVertexArrayObject = function () {
  13326. if (!this._cachedVertexArrayObject) {
  13327. return;
  13328. }
  13329. this._cachedVertexArrayObject = null;
  13330. this._gl.bindVertexArray(null);
  13331. };
  13332. /**
  13333. * Bind a list of vertex buffers to the webGL context
  13334. * @param vertexBuffers defines the list of vertex buffers to bind
  13335. * @param indexBuffer defines the index buffer to bind
  13336. * @param effect defines the effect associated with the vertex buffers
  13337. */
  13338. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13339. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13340. this._cachedVertexBuffers = vertexBuffers;
  13341. this._cachedEffectForVertexBuffers = effect;
  13342. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13343. }
  13344. this._bindIndexBufferWithCache(indexBuffer);
  13345. };
  13346. /**
  13347. * Unbind all instance attributes
  13348. */
  13349. Engine.prototype.unbindInstanceAttributes = function () {
  13350. var boundBuffer;
  13351. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13352. var instancesBuffer = this._currentInstanceBuffers[i];
  13353. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13354. boundBuffer = instancesBuffer;
  13355. this.bindArrayBuffer(instancesBuffer);
  13356. }
  13357. var offsetLocation = this._currentInstanceLocations[i];
  13358. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13359. }
  13360. this._currentInstanceBuffers.length = 0;
  13361. this._currentInstanceLocations.length = 0;
  13362. };
  13363. /**
  13364. * Release and free the memory of a vertex array object
  13365. * @param vao defines the vertex array object to delete
  13366. */
  13367. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13368. this._gl.deleteVertexArray(vao);
  13369. };
  13370. /** @hidden */
  13371. Engine.prototype._releaseBuffer = function (buffer) {
  13372. buffer.references--;
  13373. if (buffer.references === 0) {
  13374. this._gl.deleteBuffer(buffer);
  13375. return true;
  13376. }
  13377. return false;
  13378. };
  13379. /**
  13380. * Creates a webGL buffer to use with instanciation
  13381. * @param capacity defines the size of the buffer
  13382. * @returns the webGL buffer
  13383. */
  13384. Engine.prototype.createInstancesBuffer = function (capacity) {
  13385. var buffer = this._gl.createBuffer();
  13386. if (!buffer) {
  13387. throw new Error("Unable to create instance buffer");
  13388. }
  13389. buffer.capacity = capacity;
  13390. this.bindArrayBuffer(buffer);
  13391. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13392. return buffer;
  13393. };
  13394. /**
  13395. * Delete a webGL buffer used with instanciation
  13396. * @param buffer defines the webGL buffer to delete
  13397. */
  13398. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13399. this._gl.deleteBuffer(buffer);
  13400. };
  13401. /**
  13402. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13403. * @param instancesBuffer defines the webGL buffer to update and bind
  13404. * @param data defines the data to store in the buffer
  13405. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13406. */
  13407. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13408. this.bindArrayBuffer(instancesBuffer);
  13409. if (data) {
  13410. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13411. }
  13412. if (offsetLocations[0].index !== undefined) {
  13413. var stride = 0;
  13414. for (var i = 0; i < offsetLocations.length; i++) {
  13415. var ai = offsetLocations[i];
  13416. stride += ai.attributeSize * 4;
  13417. }
  13418. for (var i = 0; i < offsetLocations.length; i++) {
  13419. var ai = offsetLocations[i];
  13420. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13421. this._gl.enableVertexAttribArray(ai.index);
  13422. this._vertexAttribArraysEnabled[ai.index] = true;
  13423. }
  13424. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13425. this._gl.vertexAttribDivisor(ai.index, 1);
  13426. this._currentInstanceLocations.push(ai.index);
  13427. this._currentInstanceBuffers.push(instancesBuffer);
  13428. }
  13429. }
  13430. else {
  13431. for (var index = 0; index < 4; index++) {
  13432. var offsetLocation = offsetLocations[index];
  13433. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13434. this._gl.enableVertexAttribArray(offsetLocation);
  13435. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13436. }
  13437. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13438. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13439. this._currentInstanceLocations.push(offsetLocation);
  13440. this._currentInstanceBuffers.push(instancesBuffer);
  13441. }
  13442. }
  13443. };
  13444. /**
  13445. * Apply all cached states (depth, culling, stencil and alpha)
  13446. */
  13447. Engine.prototype.applyStates = function () {
  13448. this._depthCullingState.apply(this._gl);
  13449. this._stencilState.apply(this._gl);
  13450. this._alphaState.apply(this._gl);
  13451. };
  13452. /**
  13453. * Send a draw order
  13454. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13455. * @param indexStart defines the starting index
  13456. * @param indexCount defines the number of index to draw
  13457. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13458. */
  13459. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13460. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13461. };
  13462. /**
  13463. * Draw a list of points
  13464. * @param verticesStart defines the index of first vertex to draw
  13465. * @param verticesCount defines the count of vertices to draw
  13466. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13467. */
  13468. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13469. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13470. };
  13471. /**
  13472. * Draw a list of unindexed primitives
  13473. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13474. * @param verticesStart defines the index of first vertex to draw
  13475. * @param verticesCount defines the count of vertices to draw
  13476. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13477. */
  13478. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13479. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13480. };
  13481. /**
  13482. * Draw a list of indexed primitives
  13483. * @param fillMode defines the primitive to use
  13484. * @param indexStart defines the starting index
  13485. * @param indexCount defines the number of index to draw
  13486. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13487. */
  13488. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13489. // Apply states
  13490. this.applyStates();
  13491. this._drawCalls.addCount(1, false);
  13492. // Render
  13493. var drawMode = this._drawMode(fillMode);
  13494. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13495. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13496. if (instancesCount) {
  13497. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13498. }
  13499. else {
  13500. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13501. }
  13502. };
  13503. /**
  13504. * Draw a list of unindexed primitives
  13505. * @param fillMode defines the primitive to use
  13506. * @param verticesStart defines the index of first vertex to draw
  13507. * @param verticesCount defines the count of vertices to draw
  13508. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13509. */
  13510. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13511. // Apply states
  13512. this.applyStates();
  13513. this._drawCalls.addCount(1, false);
  13514. var drawMode = this._drawMode(fillMode);
  13515. if (instancesCount) {
  13516. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13517. }
  13518. else {
  13519. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13520. }
  13521. };
  13522. Engine.prototype._drawMode = function (fillMode) {
  13523. switch (fillMode) {
  13524. // Triangle views
  13525. case BABYLON.Material.TriangleFillMode:
  13526. return this._gl.TRIANGLES;
  13527. case BABYLON.Material.PointFillMode:
  13528. return this._gl.POINTS;
  13529. case BABYLON.Material.WireFrameFillMode:
  13530. return this._gl.LINES;
  13531. // Draw modes
  13532. case BABYLON.Material.PointListDrawMode:
  13533. return this._gl.POINTS;
  13534. case BABYLON.Material.LineListDrawMode:
  13535. return this._gl.LINES;
  13536. case BABYLON.Material.LineLoopDrawMode:
  13537. return this._gl.LINE_LOOP;
  13538. case BABYLON.Material.LineStripDrawMode:
  13539. return this._gl.LINE_STRIP;
  13540. case BABYLON.Material.TriangleStripDrawMode:
  13541. return this._gl.TRIANGLE_STRIP;
  13542. case BABYLON.Material.TriangleFanDrawMode:
  13543. return this._gl.TRIANGLE_FAN;
  13544. default:
  13545. return this._gl.TRIANGLES;
  13546. }
  13547. };
  13548. // Shaders
  13549. /** @hidden */
  13550. Engine.prototype._releaseEffect = function (effect) {
  13551. if (this._compiledEffects[effect._key]) {
  13552. delete this._compiledEffects[effect._key];
  13553. this._deleteProgram(effect.getProgram());
  13554. }
  13555. };
  13556. /** @hidden */
  13557. Engine.prototype._deleteProgram = function (program) {
  13558. if (program) {
  13559. program.__SPECTOR_rebuildProgram = null;
  13560. if (program.transformFeedback) {
  13561. this.deleteTransformFeedback(program.transformFeedback);
  13562. program.transformFeedback = null;
  13563. }
  13564. this._gl.deleteProgram(program);
  13565. }
  13566. };
  13567. /**
  13568. * Create a new effect (used to store vertex/fragment shaders)
  13569. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13570. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13571. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13572. * @param samplers defines an array of string used to represent textures
  13573. * @param defines defines the string containing the defines to use to compile the shaders
  13574. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13575. * @param onCompiled defines a function to call when the effect creation is successful
  13576. * @param onError defines a function to call when the effect creation has failed
  13577. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13578. * @returns the new Effect
  13579. */
  13580. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13581. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13582. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13583. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13584. if (this._compiledEffects[name]) {
  13585. var compiledEffect = this._compiledEffects[name];
  13586. if (onCompiled && compiledEffect.isReady()) {
  13587. onCompiled(compiledEffect);
  13588. }
  13589. return compiledEffect;
  13590. }
  13591. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13592. effect._key = name;
  13593. this._compiledEffects[name] = effect;
  13594. return effect;
  13595. };
  13596. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13597. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13598. };
  13599. ;
  13600. Engine.prototype._compileRawShader = function (source, type) {
  13601. var gl = this._gl;
  13602. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13603. gl.shaderSource(shader, source);
  13604. gl.compileShader(shader);
  13605. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13606. var log = gl.getShaderInfoLog(shader);
  13607. if (log) {
  13608. throw new Error(log);
  13609. }
  13610. }
  13611. if (!shader) {
  13612. throw new Error("Something went wrong while compile the shader.");
  13613. }
  13614. return shader;
  13615. };
  13616. ;
  13617. /**
  13618. * Directly creates a webGL program
  13619. * @param vertexCode defines the vertex shader code to use
  13620. * @param fragmentCode defines the fragment shader code to use
  13621. * @param context defines the webGL context to use (if not set, the current one will be used)
  13622. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13623. * @returns the new webGL program
  13624. */
  13625. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13626. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13627. context = context || this._gl;
  13628. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13629. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13630. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13631. };
  13632. /**
  13633. * Creates a webGL program
  13634. * @param vertexCode defines the vertex shader code to use
  13635. * @param fragmentCode defines the fragment shader code to use
  13636. * @param defines defines the string containing the defines to use to compile the shaders
  13637. * @param context defines the webGL context to use (if not set, the current one will be used)
  13638. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13639. * @returns the new webGL program
  13640. */
  13641. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13642. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13643. context = context || this._gl;
  13644. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13645. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13646. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13647. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13648. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13649. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13650. return program;
  13651. };
  13652. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13653. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13654. var shaderProgram = context.createProgram();
  13655. if (!shaderProgram) {
  13656. throw new Error("Unable to create program");
  13657. }
  13658. context.attachShader(shaderProgram, vertexShader);
  13659. context.attachShader(shaderProgram, fragmentShader);
  13660. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13661. var transformFeedback = this.createTransformFeedback();
  13662. this.bindTransformFeedback(transformFeedback);
  13663. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13664. shaderProgram.transformFeedback = transformFeedback;
  13665. }
  13666. context.linkProgram(shaderProgram);
  13667. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13668. this.bindTransformFeedback(null);
  13669. }
  13670. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13671. if (!linked) {
  13672. var error = context.getProgramInfoLog(shaderProgram);
  13673. if (error) {
  13674. throw new Error(error);
  13675. }
  13676. }
  13677. if (this.validateShaderPrograms) {
  13678. context.validateProgram(shaderProgram);
  13679. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13680. if (!validated) {
  13681. var error = context.getProgramInfoLog(shaderProgram);
  13682. if (error) {
  13683. throw new Error(error);
  13684. }
  13685. }
  13686. }
  13687. context.deleteShader(vertexShader);
  13688. context.deleteShader(fragmentShader);
  13689. return shaderProgram;
  13690. };
  13691. /**
  13692. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13693. * @param shaderProgram defines the webGL program to use
  13694. * @param uniformsNames defines the list of uniform names
  13695. * @returns an array of webGL uniform locations
  13696. */
  13697. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13698. var results = new Array();
  13699. for (var index = 0; index < uniformsNames.length; index++) {
  13700. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13701. }
  13702. return results;
  13703. };
  13704. /**
  13705. * Gets the lsit of active attributes for a given webGL program
  13706. * @param shaderProgram defines the webGL program to use
  13707. * @param attributesNames defines the list of attribute names to get
  13708. * @returns an array of indices indicating the offset of each attribute
  13709. */
  13710. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13711. var results = [];
  13712. for (var index = 0; index < attributesNames.length; index++) {
  13713. try {
  13714. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13715. }
  13716. catch (e) {
  13717. results.push(-1);
  13718. }
  13719. }
  13720. return results;
  13721. };
  13722. /**
  13723. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13724. * @param effect defines the effect to activate
  13725. */
  13726. Engine.prototype.enableEffect = function (effect) {
  13727. if (!effect) {
  13728. return;
  13729. }
  13730. // Use program
  13731. this.bindSamplers(effect);
  13732. this._currentEffect = effect;
  13733. if (effect.onBind) {
  13734. effect.onBind(effect);
  13735. }
  13736. effect.onBindObservable.notifyObservers(effect);
  13737. };
  13738. /**
  13739. * Set the value of an uniform to an array of int32
  13740. * @param uniform defines the webGL uniform location where to store the value
  13741. * @param array defines the array of int32 to store
  13742. */
  13743. Engine.prototype.setIntArray = function (uniform, array) {
  13744. if (!uniform)
  13745. return;
  13746. this._gl.uniform1iv(uniform, array);
  13747. };
  13748. /**
  13749. * Set the value of an uniform to an array of int32 (stored as vec2)
  13750. * @param uniform defines the webGL uniform location where to store the value
  13751. * @param array defines the array of int32 to store
  13752. */
  13753. Engine.prototype.setIntArray2 = function (uniform, array) {
  13754. if (!uniform || array.length % 2 !== 0)
  13755. return;
  13756. this._gl.uniform2iv(uniform, array);
  13757. };
  13758. /**
  13759. * Set the value of an uniform to an array of int32 (stored as vec3)
  13760. * @param uniform defines the webGL uniform location where to store the value
  13761. * @param array defines the array of int32 to store
  13762. */
  13763. Engine.prototype.setIntArray3 = function (uniform, array) {
  13764. if (!uniform || array.length % 3 !== 0)
  13765. return;
  13766. this._gl.uniform3iv(uniform, array);
  13767. };
  13768. /**
  13769. * Set the value of an uniform to an array of int32 (stored as vec4)
  13770. * @param uniform defines the webGL uniform location where to store the value
  13771. * @param array defines the array of int32 to store
  13772. */
  13773. Engine.prototype.setIntArray4 = function (uniform, array) {
  13774. if (!uniform || array.length % 4 !== 0)
  13775. return;
  13776. this._gl.uniform4iv(uniform, array);
  13777. };
  13778. /**
  13779. * Set the value of an uniform to an array of float32
  13780. * @param uniform defines the webGL uniform location where to store the value
  13781. * @param array defines the array of float32 to store
  13782. */
  13783. Engine.prototype.setFloatArray = function (uniform, array) {
  13784. if (!uniform)
  13785. return;
  13786. this._gl.uniform1fv(uniform, array);
  13787. };
  13788. /**
  13789. * Set the value of an uniform to an array of float32 (stored as vec2)
  13790. * @param uniform defines the webGL uniform location where to store the value
  13791. * @param array defines the array of float32 to store
  13792. */
  13793. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13794. if (!uniform || array.length % 2 !== 0)
  13795. return;
  13796. this._gl.uniform2fv(uniform, array);
  13797. };
  13798. /**
  13799. * Set the value of an uniform to an array of float32 (stored as vec3)
  13800. * @param uniform defines the webGL uniform location where to store the value
  13801. * @param array defines the array of float32 to store
  13802. */
  13803. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13804. if (!uniform || array.length % 3 !== 0)
  13805. return;
  13806. this._gl.uniform3fv(uniform, array);
  13807. };
  13808. /**
  13809. * Set the value of an uniform to an array of float32 (stored as vec4)
  13810. * @param uniform defines the webGL uniform location where to store the value
  13811. * @param array defines the array of float32 to store
  13812. */
  13813. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13814. if (!uniform || array.length % 4 !== 0)
  13815. return;
  13816. this._gl.uniform4fv(uniform, array);
  13817. };
  13818. /**
  13819. * Set the value of an uniform to an array of number
  13820. * @param uniform defines the webGL uniform location where to store the value
  13821. * @param array defines the array of number to store
  13822. */
  13823. Engine.prototype.setArray = function (uniform, array) {
  13824. if (!uniform)
  13825. return;
  13826. this._gl.uniform1fv(uniform, array);
  13827. };
  13828. /**
  13829. * Set the value of an uniform to an array of number (stored as vec2)
  13830. * @param uniform defines the webGL uniform location where to store the value
  13831. * @param array defines the array of number to store
  13832. */
  13833. Engine.prototype.setArray2 = function (uniform, array) {
  13834. if (!uniform || array.length % 2 !== 0)
  13835. return;
  13836. this._gl.uniform2fv(uniform, array);
  13837. };
  13838. /**
  13839. * Set the value of an uniform to an array of number (stored as vec3)
  13840. * @param uniform defines the webGL uniform location where to store the value
  13841. * @param array defines the array of number to store
  13842. */
  13843. Engine.prototype.setArray3 = function (uniform, array) {
  13844. if (!uniform || array.length % 3 !== 0)
  13845. return;
  13846. this._gl.uniform3fv(uniform, array);
  13847. };
  13848. /**
  13849. * Set the value of an uniform to an array of number (stored as vec4)
  13850. * @param uniform defines the webGL uniform location where to store the value
  13851. * @param array defines the array of number to store
  13852. */
  13853. Engine.prototype.setArray4 = function (uniform, array) {
  13854. if (!uniform || array.length % 4 !== 0)
  13855. return;
  13856. this._gl.uniform4fv(uniform, array);
  13857. };
  13858. /**
  13859. * Set the value of an uniform to an array of float32 (stored as matrices)
  13860. * @param uniform defines the webGL uniform location where to store the value
  13861. * @param matrices defines the array of float32 to store
  13862. */
  13863. Engine.prototype.setMatrices = function (uniform, matrices) {
  13864. if (!uniform)
  13865. return;
  13866. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13867. };
  13868. /**
  13869. * Set the value of an uniform to a matrix
  13870. * @param uniform defines the webGL uniform location where to store the value
  13871. * @param matrix defines the matrix to store
  13872. */
  13873. Engine.prototype.setMatrix = function (uniform, matrix) {
  13874. if (!uniform)
  13875. return;
  13876. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13877. };
  13878. /**
  13879. * Set the value of an uniform to a matrix (3x3)
  13880. * @param uniform defines the webGL uniform location where to store the value
  13881. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13882. */
  13883. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13884. if (!uniform)
  13885. return;
  13886. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13887. };
  13888. /**
  13889. * Set the value of an uniform to a matrix (2x2)
  13890. * @param uniform defines the webGL uniform location where to store the value
  13891. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13892. */
  13893. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13894. if (!uniform)
  13895. return;
  13896. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13897. };
  13898. /**
  13899. * Set the value of an uniform to a number (int)
  13900. * @param uniform defines the webGL uniform location where to store the value
  13901. * @param value defines the int number to store
  13902. */
  13903. Engine.prototype.setInt = function (uniform, value) {
  13904. if (!uniform)
  13905. return;
  13906. this._gl.uniform1i(uniform, value);
  13907. };
  13908. /**
  13909. * Set the value of an uniform to a number (float)
  13910. * @param uniform defines the webGL uniform location where to store the value
  13911. * @param value defines the float number to store
  13912. */
  13913. Engine.prototype.setFloat = function (uniform, value) {
  13914. if (!uniform)
  13915. return;
  13916. this._gl.uniform1f(uniform, value);
  13917. };
  13918. /**
  13919. * Set the value of an uniform to a vec2
  13920. * @param uniform defines the webGL uniform location where to store the value
  13921. * @param x defines the 1st component of the value
  13922. * @param y defines the 2nd component of the value
  13923. */
  13924. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniform2f(uniform, x, y);
  13928. };
  13929. /**
  13930. * Set the value of an uniform to a vec3
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param x defines the 1st component of the value
  13933. * @param y defines the 2nd component of the value
  13934. * @param z defines the 3rd component of the value
  13935. */
  13936. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13937. if (!uniform)
  13938. return;
  13939. this._gl.uniform3f(uniform, x, y, z);
  13940. };
  13941. /**
  13942. * Set the value of an uniform to a boolean
  13943. * @param uniform defines the webGL uniform location where to store the value
  13944. * @param bool defines the boolean to store
  13945. */
  13946. Engine.prototype.setBool = function (uniform, bool) {
  13947. if (!uniform)
  13948. return;
  13949. this._gl.uniform1i(uniform, bool);
  13950. };
  13951. /**
  13952. * Set the value of an uniform to a vec4
  13953. * @param uniform defines the webGL uniform location where to store the value
  13954. * @param x defines the 1st component of the value
  13955. * @param y defines the 2nd component of the value
  13956. * @param z defines the 3rd component of the value
  13957. * @param w defines the 4th component of the value
  13958. */
  13959. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13960. if (!uniform)
  13961. return;
  13962. this._gl.uniform4f(uniform, x, y, z, w);
  13963. };
  13964. /**
  13965. * Set the value of an uniform to a Color3
  13966. * @param uniform defines the webGL uniform location where to store the value
  13967. * @param color3 defines the color to store
  13968. */
  13969. Engine.prototype.setColor3 = function (uniform, color3) {
  13970. if (!uniform)
  13971. return;
  13972. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13973. };
  13974. /**
  13975. * Set the value of an uniform to a Color3 and an alpha value
  13976. * @param uniform defines the webGL uniform location where to store the value
  13977. * @param color3 defines the color to store
  13978. * @param alpha defines the alpha component to store
  13979. */
  13980. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13981. if (!uniform)
  13982. return;
  13983. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13984. };
  13985. /**
  13986. * Sets a Color4 on a uniform variable
  13987. * @param uniform defines the uniform location
  13988. * @param color4 defines the value to be set
  13989. */
  13990. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13991. if (!uniform)
  13992. return;
  13993. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13994. };
  13995. // States
  13996. /**
  13997. * Set various states to the webGL context
  13998. * @param culling defines backface culling state
  13999. * @param zOffset defines the value to apply to zOffset (0 by default)
  14000. * @param force defines if states must be applied even if cache is up to date
  14001. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14002. */
  14003. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14004. if (zOffset === void 0) { zOffset = 0; }
  14005. if (reverseSide === void 0) { reverseSide = false; }
  14006. // Culling
  14007. if (this._depthCullingState.cull !== culling || force) {
  14008. this._depthCullingState.cull = culling;
  14009. }
  14010. // Cull face
  14011. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14012. if (this._depthCullingState.cullFace !== cullFace || force) {
  14013. this._depthCullingState.cullFace = cullFace;
  14014. }
  14015. // Z offset
  14016. this.setZOffset(zOffset);
  14017. // Front face
  14018. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14019. if (this._depthCullingState.frontFace !== frontFace || force) {
  14020. this._depthCullingState.frontFace = frontFace;
  14021. }
  14022. };
  14023. /**
  14024. * Set the z offset to apply to current rendering
  14025. * @param value defines the offset to apply
  14026. */
  14027. Engine.prototype.setZOffset = function (value) {
  14028. this._depthCullingState.zOffset = value;
  14029. };
  14030. /**
  14031. * Gets the current value of the zOffset
  14032. * @returns the current zOffset state
  14033. */
  14034. Engine.prototype.getZOffset = function () {
  14035. return this._depthCullingState.zOffset;
  14036. };
  14037. /**
  14038. * Enable or disable depth buffering
  14039. * @param enable defines the state to set
  14040. */
  14041. Engine.prototype.setDepthBuffer = function (enable) {
  14042. this._depthCullingState.depthTest = enable;
  14043. };
  14044. /**
  14045. * Gets a boolean indicating if depth writing is enabled
  14046. * @returns the current depth writing state
  14047. */
  14048. Engine.prototype.getDepthWrite = function () {
  14049. return this._depthCullingState.depthMask;
  14050. };
  14051. /**
  14052. * Enable or disable depth writing
  14053. * @param enable defines the state to set
  14054. */
  14055. Engine.prototype.setDepthWrite = function (enable) {
  14056. this._depthCullingState.depthMask = enable;
  14057. };
  14058. /**
  14059. * Enable or disable color writing
  14060. * @param enable defines the state to set
  14061. */
  14062. Engine.prototype.setColorWrite = function (enable) {
  14063. this._gl.colorMask(enable, enable, enable, enable);
  14064. this._colorWrite = enable;
  14065. };
  14066. /**
  14067. * Gets a boolean indicating if color writing is enabled
  14068. * @returns the current color writing state
  14069. */
  14070. Engine.prototype.getColorWrite = function () {
  14071. return this._colorWrite;
  14072. };
  14073. /**
  14074. * Sets alpha constants used by some alpha blending modes
  14075. * @param r defines the red component
  14076. * @param g defines the green component
  14077. * @param b defines the blue component
  14078. * @param a defines the alpha component
  14079. */
  14080. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14081. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14082. };
  14083. /**
  14084. * Sets the current alpha mode
  14085. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14086. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14087. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14088. */
  14089. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14090. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14091. if (this._alphaMode === mode) {
  14092. return;
  14093. }
  14094. switch (mode) {
  14095. case Engine.ALPHA_DISABLE:
  14096. this._alphaState.alphaBlend = false;
  14097. break;
  14098. case Engine.ALPHA_PREMULTIPLIED:
  14099. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14100. this._alphaState.alphaBlend = true;
  14101. break;
  14102. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14103. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14104. this._alphaState.alphaBlend = true;
  14105. break;
  14106. case Engine.ALPHA_COMBINE:
  14107. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14108. this._alphaState.alphaBlend = true;
  14109. break;
  14110. case Engine.ALPHA_ONEONE:
  14111. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14112. this._alphaState.alphaBlend = true;
  14113. break;
  14114. case Engine.ALPHA_ADD:
  14115. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14116. this._alphaState.alphaBlend = true;
  14117. break;
  14118. case Engine.ALPHA_SUBTRACT:
  14119. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14120. this._alphaState.alphaBlend = true;
  14121. break;
  14122. case Engine.ALPHA_MULTIPLY:
  14123. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14124. this._alphaState.alphaBlend = true;
  14125. break;
  14126. case Engine.ALPHA_MAXIMIZED:
  14127. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14128. this._alphaState.alphaBlend = true;
  14129. break;
  14130. case Engine.ALPHA_INTERPOLATE:
  14131. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14132. this._alphaState.alphaBlend = true;
  14133. break;
  14134. case Engine.ALPHA_SCREENMODE:
  14135. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14136. this._alphaState.alphaBlend = true;
  14137. break;
  14138. }
  14139. if (!noDepthWriteChange) {
  14140. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14141. }
  14142. this._alphaMode = mode;
  14143. };
  14144. /**
  14145. * Gets the current alpha mode
  14146. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14147. * @returns the current alpha mode
  14148. */
  14149. Engine.prototype.getAlphaMode = function () {
  14150. return this._alphaMode;
  14151. };
  14152. // Textures
  14153. /**
  14154. * Clears the list of texture accessible through engine.
  14155. * This can help preventing texture load conflict due to name collision.
  14156. */
  14157. Engine.prototype.clearInternalTexturesCache = function () {
  14158. this._internalTexturesCache = [];
  14159. };
  14160. /**
  14161. * Force the entire cache to be cleared
  14162. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14163. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14164. */
  14165. Engine.prototype.wipeCaches = function (bruteForce) {
  14166. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14167. return;
  14168. }
  14169. this._currentEffect = null;
  14170. this._unpackFlipYCached = null;
  14171. this._viewportCached.x = 0;
  14172. this._viewportCached.y = 0;
  14173. this._viewportCached.z = 0;
  14174. this._viewportCached.w = 0;
  14175. if (bruteForce) {
  14176. this.resetTextureCache();
  14177. this._currentProgram = null;
  14178. this._stencilState.reset();
  14179. this._depthCullingState.reset();
  14180. this.setDepthFunctionToLessOrEqual();
  14181. this._alphaState.reset();
  14182. }
  14183. this._resetVertexBufferBinding();
  14184. this._cachedIndexBuffer = null;
  14185. this._cachedEffectForVertexBuffers = null;
  14186. this._unbindVertexArrayObject();
  14187. this.bindIndexBuffer(null);
  14188. };
  14189. /**
  14190. * Set the compressed texture format to use, based on the formats you have, and the formats
  14191. * supported by the hardware / browser.
  14192. *
  14193. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14194. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14195. * to API arguments needed to compressed textures. This puts the burden on the container
  14196. * generator to house the arcane code for determining these for current & future formats.
  14197. *
  14198. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14199. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14200. *
  14201. * Note: The result of this call is not taken into account when a texture is base64.
  14202. *
  14203. * @param formatsAvailable defines the list of those format families you have created
  14204. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14205. *
  14206. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14207. * @returns The extension selected.
  14208. */
  14209. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14210. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14211. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14212. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14213. return this._textureFormatInUse = this._texturesSupported[i];
  14214. }
  14215. }
  14216. }
  14217. // actively set format to nothing, to allow this to be called more than once
  14218. // and possibly fail the 2nd time
  14219. this._textureFormatInUse = null;
  14220. return null;
  14221. };
  14222. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14223. var gl = this._gl;
  14224. var magFilter = gl.NEAREST;
  14225. var minFilter = gl.NEAREST;
  14226. switch (samplingMode) {
  14227. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14228. magFilter = gl.LINEAR;
  14229. if (generateMipMaps) {
  14230. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14231. }
  14232. else {
  14233. minFilter = gl.LINEAR;
  14234. }
  14235. break;
  14236. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14237. magFilter = gl.LINEAR;
  14238. if (generateMipMaps) {
  14239. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14240. }
  14241. else {
  14242. minFilter = gl.LINEAR;
  14243. }
  14244. break;
  14245. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14246. magFilter = gl.NEAREST;
  14247. if (generateMipMaps) {
  14248. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14249. }
  14250. else {
  14251. minFilter = gl.NEAREST;
  14252. }
  14253. break;
  14254. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14255. magFilter = gl.NEAREST;
  14256. if (generateMipMaps) {
  14257. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14258. }
  14259. else {
  14260. minFilter = gl.NEAREST;
  14261. }
  14262. break;
  14263. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14264. magFilter = gl.NEAREST;
  14265. if (generateMipMaps) {
  14266. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14267. }
  14268. else {
  14269. minFilter = gl.LINEAR;
  14270. }
  14271. break;
  14272. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14273. magFilter = gl.NEAREST;
  14274. if (generateMipMaps) {
  14275. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14276. }
  14277. else {
  14278. minFilter = gl.LINEAR;
  14279. }
  14280. break;
  14281. case Engine.TEXTURE_NEAREST_LINEAR:
  14282. magFilter = gl.NEAREST;
  14283. minFilter = gl.LINEAR;
  14284. break;
  14285. case Engine.TEXTURE_NEAREST_NEAREST:
  14286. magFilter = gl.NEAREST;
  14287. minFilter = gl.NEAREST;
  14288. break;
  14289. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14290. magFilter = gl.LINEAR;
  14291. if (generateMipMaps) {
  14292. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14293. }
  14294. else {
  14295. minFilter = gl.NEAREST;
  14296. }
  14297. break;
  14298. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14299. magFilter = gl.LINEAR;
  14300. if (generateMipMaps) {
  14301. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14302. }
  14303. else {
  14304. minFilter = gl.NEAREST;
  14305. }
  14306. break;
  14307. case Engine.TEXTURE_LINEAR_LINEAR:
  14308. magFilter = gl.LINEAR;
  14309. minFilter = gl.LINEAR;
  14310. break;
  14311. case Engine.TEXTURE_LINEAR_NEAREST:
  14312. magFilter = gl.LINEAR;
  14313. minFilter = gl.NEAREST;
  14314. break;
  14315. }
  14316. return {
  14317. min: minFilter,
  14318. mag: magFilter
  14319. };
  14320. };
  14321. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14322. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14323. var img;
  14324. var onload = function () {
  14325. loadedImages[index] = img;
  14326. loadedImages._internalCount++;
  14327. if (scene) {
  14328. scene._removePendingData(img);
  14329. }
  14330. if (loadedImages._internalCount === 6) {
  14331. onfinish(loadedImages);
  14332. }
  14333. };
  14334. var onerror = function (message, exception) {
  14335. if (scene) {
  14336. scene._removePendingData(img);
  14337. }
  14338. if (onErrorCallBack) {
  14339. onErrorCallBack(message, exception);
  14340. }
  14341. };
  14342. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14343. if (scene) {
  14344. scene._addPendingData(img);
  14345. }
  14346. };
  14347. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14348. if (onError === void 0) { onError = null; }
  14349. var loadedImages = [];
  14350. loadedImages._internalCount = 0;
  14351. for (var index = 0; index < 6; index++) {
  14352. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14353. }
  14354. };
  14355. ;
  14356. /** @hidden */
  14357. Engine.prototype._createTexture = function () {
  14358. var texture = this._gl.createTexture();
  14359. if (!texture) {
  14360. throw new Error("Unable to create texture");
  14361. }
  14362. return texture;
  14363. };
  14364. /**
  14365. * Usually called from BABYLON.Texture.ts.
  14366. * Passed information to create a WebGLTexture
  14367. * @param urlArg defines a value which contains one of the following:
  14368. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14369. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14370. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14371. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14372. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14373. * @param scene needed for loading to the correct scene
  14374. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14375. * @param onLoad optional callback to be called upon successful completion
  14376. * @param onError optional callback to be called upon failure
  14377. * @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
  14378. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14379. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14380. * @param forcedExtension defines the extension to use to pick the right loader
  14381. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14382. */
  14383. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14384. var _this = this;
  14385. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14386. if (onLoad === void 0) { onLoad = null; }
  14387. if (onError === void 0) { onError = null; }
  14388. if (buffer === void 0) { buffer = null; }
  14389. if (fallback === void 0) { fallback = null; }
  14390. if (format === void 0) { format = null; }
  14391. if (forcedExtension === void 0) { forcedExtension = null; }
  14392. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14393. var fromData = url.substr(0, 5) === "data:";
  14394. var fromBlob = url.substr(0, 5) === "blob:";
  14395. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14396. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14397. // establish the file extension, if possible
  14398. var lastDot = url.lastIndexOf('.');
  14399. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14400. var loader = null;
  14401. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14402. var availableLoader = _a[_i];
  14403. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14404. loader = availableLoader;
  14405. break;
  14406. }
  14407. }
  14408. if (loader) {
  14409. url = loader.transformUrl(url, this._textureFormatInUse);
  14410. }
  14411. if (scene) {
  14412. scene._addPendingData(texture);
  14413. }
  14414. texture.url = url;
  14415. texture.generateMipMaps = !noMipmap;
  14416. texture.samplingMode = samplingMode;
  14417. texture.invertY = invertY;
  14418. if (!this._doNotHandleContextLost) {
  14419. // Keep a link to the buffer only if we plan to handle context lost
  14420. texture._buffer = buffer;
  14421. }
  14422. var onLoadObserver = null;
  14423. if (onLoad && !fallback) {
  14424. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14425. }
  14426. if (!fallback)
  14427. this._internalTexturesCache.push(texture);
  14428. var onInternalError = function (message, exception) {
  14429. if (scene) {
  14430. scene._removePendingData(texture);
  14431. }
  14432. var customFallback = false;
  14433. if (loader) {
  14434. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14435. if (fallbackUrl) {
  14436. // Add Back
  14437. customFallback = true;
  14438. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14439. }
  14440. }
  14441. if (!customFallback) {
  14442. if (onLoadObserver) {
  14443. texture.onLoadedObservable.remove(onLoadObserver);
  14444. }
  14445. if (BABYLON.Tools.UseFallbackTexture) {
  14446. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14447. }
  14448. }
  14449. if (onError) {
  14450. onError(message || "Unknown error", exception);
  14451. }
  14452. };
  14453. // processing for non-image formats
  14454. if (loader) {
  14455. var callback = function (data) {
  14456. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14457. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14458. done();
  14459. return false;
  14460. }, samplingMode);
  14461. });
  14462. };
  14463. if (!buffer) {
  14464. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14465. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14466. });
  14467. }
  14468. else {
  14469. callback(buffer);
  14470. }
  14471. }
  14472. else {
  14473. var onload = function (img) {
  14474. if (fromBlob && !_this._doNotHandleContextLost) {
  14475. // We need to store the image if we need to rebuild the texture
  14476. // in case of a webgl context lost
  14477. texture._buffer = img;
  14478. }
  14479. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14480. var gl = _this._gl;
  14481. var isPot = (img.width === potWidth && img.height === potHeight);
  14482. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14483. if (isPot) {
  14484. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14485. return false;
  14486. }
  14487. var maxTextureSize = _this._caps.maxTextureSize;
  14488. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14489. _this._prepareWorkingCanvas();
  14490. if (!_this._workingCanvas || !_this._workingContext) {
  14491. return false;
  14492. }
  14493. _this._workingCanvas.width = potWidth;
  14494. _this._workingCanvas.height = potHeight;
  14495. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14496. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14497. texture.width = potWidth;
  14498. texture.height = potHeight;
  14499. return false;
  14500. }
  14501. else {
  14502. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14503. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14504. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14505. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14507. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14510. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14511. _this._releaseTexture(source_1);
  14512. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14513. continuationCallback();
  14514. });
  14515. }
  14516. return true;
  14517. }, samplingMode);
  14518. };
  14519. if (!fromData || isBase64) {
  14520. if (buffer instanceof HTMLImageElement) {
  14521. onload(buffer);
  14522. }
  14523. else {
  14524. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14525. }
  14526. }
  14527. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14528. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14529. }
  14530. else {
  14531. onload(buffer);
  14532. }
  14533. }
  14534. return texture;
  14535. };
  14536. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14537. var _this = this;
  14538. var rtt = this.createRenderTargetTexture({
  14539. width: destination.width,
  14540. height: destination.height,
  14541. }, {
  14542. generateMipMaps: false,
  14543. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14544. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14545. generateDepthBuffer: false,
  14546. generateStencilBuffer: false
  14547. });
  14548. if (!this._rescalePostProcess) {
  14549. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14550. }
  14551. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14552. _this._rescalePostProcess.onApply = function (effect) {
  14553. effect._bindTexture("textureSampler", source);
  14554. };
  14555. var hostingScene = scene;
  14556. if (!hostingScene) {
  14557. hostingScene = _this.scenes[_this.scenes.length - 1];
  14558. }
  14559. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14560. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14561. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14562. _this.unBindFramebuffer(rtt);
  14563. _this._releaseTexture(rtt);
  14564. if (onComplete) {
  14565. onComplete();
  14566. }
  14567. });
  14568. };
  14569. /**
  14570. * Update a raw texture
  14571. * @param texture defines the texture to update
  14572. * @param data defines the data to store in the texture
  14573. * @param format defines the format of the data
  14574. * @param invertY defines if data must be stored with Y axis inverted
  14575. * @param compression defines the compression used (null by default)
  14576. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14577. */
  14578. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14579. if (compression === void 0) { compression = null; }
  14580. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14581. if (!texture) {
  14582. return;
  14583. }
  14584. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14585. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14586. // babylon's internalFormat but gl's texImage2D format
  14587. var internalFormat = this._getInternalFormat(format);
  14588. var textureType = this._getWebGLTextureType(type);
  14589. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14590. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14591. if (!this._doNotHandleContextLost) {
  14592. texture._bufferView = data;
  14593. texture.format = format;
  14594. texture.type = type;
  14595. texture.invertY = invertY;
  14596. texture._compression = compression;
  14597. }
  14598. if (texture.width % 4 !== 0) {
  14599. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14600. }
  14601. if (compression && data) {
  14602. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14603. }
  14604. else {
  14605. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14606. }
  14607. if (texture.generateMipMaps) {
  14608. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14609. }
  14610. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14611. // this.resetTextureCache();
  14612. texture.isReady = true;
  14613. };
  14614. /**
  14615. * Creates a raw texture
  14616. * @param data defines the data to store in the texture
  14617. * @param width defines the width of the texture
  14618. * @param height defines the height of the texture
  14619. * @param format defines the format of the data
  14620. * @param generateMipMaps defines if the engine should generate the mip levels
  14621. * @param invertY defines if data must be stored with Y axis inverted
  14622. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14623. * @param compression defines the compression used (null by default)
  14624. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14625. * @returns the raw texture inside an InternalTexture
  14626. */
  14627. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14628. if (compression === void 0) { compression = null; }
  14629. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14630. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14631. texture.baseWidth = width;
  14632. texture.baseHeight = height;
  14633. texture.width = width;
  14634. texture.height = height;
  14635. texture.format = format;
  14636. texture.generateMipMaps = generateMipMaps;
  14637. texture.samplingMode = samplingMode;
  14638. texture.invertY = invertY;
  14639. texture._compression = compression;
  14640. texture.type = type;
  14641. if (!this._doNotHandleContextLost) {
  14642. texture._bufferView = data;
  14643. }
  14644. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14645. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14646. // Filters
  14647. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14648. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14649. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14650. if (generateMipMaps) {
  14651. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14652. }
  14653. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14654. this._internalTexturesCache.push(texture);
  14655. return texture;
  14656. };
  14657. /** @hidden */
  14658. Engine.prototype._unpackFlipY = function (value) {
  14659. if (this._unpackFlipYCached !== value) {
  14660. this._unpackFlipYCached = value;
  14661. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14662. }
  14663. };
  14664. /** @hidden */
  14665. Engine.prototype._getUnpackAlignement = function () {
  14666. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14667. };
  14668. /**
  14669. * Creates a dynamic texture
  14670. * @param width defines the width of the texture
  14671. * @param height defines the height of the texture
  14672. * @param generateMipMaps defines if the engine should generate the mip levels
  14673. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14674. * @returns the dynamic texture inside an InternalTexture
  14675. */
  14676. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14677. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14678. texture.baseWidth = width;
  14679. texture.baseHeight = height;
  14680. if (generateMipMaps) {
  14681. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14682. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14683. }
  14684. // this.resetTextureCache();
  14685. texture.width = width;
  14686. texture.height = height;
  14687. texture.isReady = false;
  14688. texture.generateMipMaps = generateMipMaps;
  14689. texture.samplingMode = samplingMode;
  14690. this.updateTextureSamplingMode(samplingMode, texture);
  14691. this._internalTexturesCache.push(texture);
  14692. return texture;
  14693. };
  14694. /**
  14695. * Update the sampling mode of a given texture
  14696. * @param samplingMode defines the required sampling mode
  14697. * @param texture defines the texture to update
  14698. */
  14699. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14700. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14701. if (texture.isCube) {
  14702. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14703. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14704. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14705. }
  14706. else if (texture.is3D) {
  14707. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14708. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14709. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14710. }
  14711. else {
  14712. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14713. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14714. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14715. }
  14716. texture.samplingMode = samplingMode;
  14717. };
  14718. /**
  14719. * Update the content of a dynamic texture
  14720. * @param texture defines the texture to update
  14721. * @param canvas defines the canvas containing the source
  14722. * @param invertY defines if data must be stored with Y axis inverted
  14723. * @param premulAlpha defines if alpha is stored as premultiplied
  14724. * @param format defines the format of the data
  14725. */
  14726. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14727. if (premulAlpha === void 0) { premulAlpha = false; }
  14728. if (!texture) {
  14729. return;
  14730. }
  14731. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14732. this._unpackFlipY(invertY);
  14733. if (premulAlpha) {
  14734. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14735. }
  14736. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14737. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14738. if (texture.generateMipMaps) {
  14739. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14740. }
  14741. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14742. if (premulAlpha) {
  14743. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14744. }
  14745. texture.isReady = true;
  14746. };
  14747. /**
  14748. * Update a video texture
  14749. * @param texture defines the texture to update
  14750. * @param video defines the video element to use
  14751. * @param invertY defines if data must be stored with Y axis inverted
  14752. */
  14753. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14754. if (!texture || texture._isDisabled) {
  14755. return;
  14756. }
  14757. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14758. this._unpackFlipY(!invertY); // Video are upside down by default
  14759. try {
  14760. // Testing video texture support
  14761. if (this._videoTextureSupported === undefined) {
  14762. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14763. if (this._gl.getError() !== 0) {
  14764. this._videoTextureSupported = false;
  14765. }
  14766. else {
  14767. this._videoTextureSupported = true;
  14768. }
  14769. }
  14770. // Copy video through the current working canvas if video texture is not supported
  14771. if (!this._videoTextureSupported) {
  14772. if (!texture._workingCanvas) {
  14773. texture._workingCanvas = document.createElement("canvas");
  14774. var context = texture._workingCanvas.getContext("2d");
  14775. if (!context) {
  14776. throw new Error("Unable to get 2d context");
  14777. }
  14778. texture._workingContext = context;
  14779. texture._workingCanvas.width = texture.width;
  14780. texture._workingCanvas.height = texture.height;
  14781. }
  14782. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14783. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14784. }
  14785. else {
  14786. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14787. }
  14788. if (texture.generateMipMaps) {
  14789. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14790. }
  14791. if (!wasPreviouslyBound) {
  14792. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14793. }
  14794. // this.resetTextureCache();
  14795. texture.isReady = true;
  14796. }
  14797. catch (ex) {
  14798. // Something unexpected
  14799. // Let's disable the texture
  14800. texture._isDisabled = true;
  14801. }
  14802. };
  14803. /**
  14804. * Updates a depth texture Comparison Mode and Function.
  14805. * If the comparison Function is equal to 0, the mode will be set to none.
  14806. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14807. * @param texture The texture to set the comparison function for
  14808. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14809. */
  14810. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14811. if (this.webGLVersion === 1) {
  14812. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14813. return;
  14814. }
  14815. var gl = this._gl;
  14816. if (texture.isCube) {
  14817. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14818. if (comparisonFunction === 0) {
  14819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14821. }
  14822. else {
  14823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14825. }
  14826. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14827. }
  14828. else {
  14829. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14830. if (comparisonFunction === 0) {
  14831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14833. }
  14834. else {
  14835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14836. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14837. }
  14838. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14839. }
  14840. texture._comparisonFunction = comparisonFunction;
  14841. };
  14842. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14843. var width = size.width || size;
  14844. var height = size.height || size;
  14845. internalTexture.baseWidth = width;
  14846. internalTexture.baseHeight = height;
  14847. internalTexture.width = width;
  14848. internalTexture.height = height;
  14849. internalTexture.isReady = true;
  14850. internalTexture.samples = 1;
  14851. internalTexture.generateMipMaps = false;
  14852. internalTexture._generateDepthBuffer = true;
  14853. internalTexture._generateStencilBuffer = generateStencil;
  14854. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14855. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14856. internalTexture._comparisonFunction = comparisonFunction;
  14857. var gl = this._gl;
  14858. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14859. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14860. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14861. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14862. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14863. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14864. if (comparisonFunction === 0) {
  14865. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14866. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14867. }
  14868. else {
  14869. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14870. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14871. }
  14872. };
  14873. /**
  14874. * Creates a depth stencil texture.
  14875. * This is only available in WebGL 2 or with the depth texture extension available.
  14876. * @param size The size of face edge in the texture.
  14877. * @param options The options defining the texture.
  14878. * @returns The texture
  14879. */
  14880. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14881. if (options.isCube) {
  14882. var width = size.width || size;
  14883. return this._createDepthStencilCubeTexture(width, options);
  14884. }
  14885. else {
  14886. return this._createDepthStencilTexture(size, options);
  14887. }
  14888. };
  14889. /**
  14890. * Creates a depth stencil texture.
  14891. * This is only available in WebGL 2 or with the depth texture extension available.
  14892. * @param size The size of face edge in the texture.
  14893. * @param options The options defining the texture.
  14894. * @returns The texture
  14895. */
  14896. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14897. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14898. if (!this._caps.depthTextureExtension) {
  14899. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14900. return internalTexture;
  14901. }
  14902. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14903. var gl = this._gl;
  14904. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14905. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14906. if (this.webGLVersion > 1) {
  14907. if (internalOptions.generateStencil) {
  14908. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14909. }
  14910. else {
  14911. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14912. }
  14913. }
  14914. else {
  14915. if (internalOptions.generateStencil) {
  14916. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14917. }
  14918. else {
  14919. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14920. }
  14921. }
  14922. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14923. return internalTexture;
  14924. };
  14925. /**
  14926. * Creates a depth stencil cube texture.
  14927. * This is only available in WebGL 2.
  14928. * @param size The size of face edge in the cube texture.
  14929. * @param options The options defining the cube texture.
  14930. * @returns The cube texture
  14931. */
  14932. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14933. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14934. internalTexture.isCube = true;
  14935. if (this.webGLVersion === 1) {
  14936. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14937. return internalTexture;
  14938. }
  14939. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14940. var gl = this._gl;
  14941. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14942. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14943. // Create the depth/stencil buffer
  14944. for (var face = 0; face < 6; face++) {
  14945. if (internalOptions.generateStencil) {
  14946. 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);
  14947. }
  14948. else {
  14949. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14950. }
  14951. }
  14952. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14953. return internalTexture;
  14954. };
  14955. /**
  14956. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14957. * @param renderTarget The render target to set the frame buffer for
  14958. */
  14959. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14960. // Create the framebuffer
  14961. var internalTexture = renderTarget.getInternalTexture();
  14962. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14963. return;
  14964. }
  14965. var gl = this._gl;
  14966. var depthStencilTexture = renderTarget.depthStencilTexture;
  14967. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14968. if (depthStencilTexture.isCube) {
  14969. if (depthStencilTexture._generateStencilBuffer) {
  14970. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14971. }
  14972. else {
  14973. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14974. }
  14975. }
  14976. else {
  14977. if (depthStencilTexture._generateStencilBuffer) {
  14978. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14979. }
  14980. else {
  14981. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14982. }
  14983. }
  14984. this.bindUnboundFramebuffer(null);
  14985. };
  14986. /**
  14987. * Creates a new render target texture
  14988. * @param size defines the size of the texture
  14989. * @param options defines the options used to create the texture
  14990. * @returns a new render target texture stored in an InternalTexture
  14991. */
  14992. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14993. var fullOptions = new RenderTargetCreationOptions();
  14994. if (options !== undefined && typeof options === "object") {
  14995. fullOptions.generateMipMaps = options.generateMipMaps;
  14996. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14997. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14998. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14999. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15000. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15001. }
  15002. else {
  15003. fullOptions.generateMipMaps = options;
  15004. fullOptions.generateDepthBuffer = true;
  15005. fullOptions.generateStencilBuffer = false;
  15006. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15007. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15008. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15009. }
  15010. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15011. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15012. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15013. }
  15014. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15015. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15016. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15017. }
  15018. var gl = this._gl;
  15019. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15020. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15021. var width = size.width || size;
  15022. var height = size.height || size;
  15023. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15024. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15025. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15026. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15027. }
  15028. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15029. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15032. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15033. // Create the framebuffer
  15034. var currentFrameBuffer = this._currentFramebuffer;
  15035. var framebuffer = gl.createFramebuffer();
  15036. this.bindUnboundFramebuffer(framebuffer);
  15037. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15038. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15039. if (fullOptions.generateMipMaps) {
  15040. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15041. }
  15042. // Unbind
  15043. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15044. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15045. this.bindUnboundFramebuffer(currentFrameBuffer);
  15046. texture._framebuffer = framebuffer;
  15047. texture.baseWidth = width;
  15048. texture.baseHeight = height;
  15049. texture.width = width;
  15050. texture.height = height;
  15051. texture.isReady = true;
  15052. texture.samples = 1;
  15053. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15054. texture.samplingMode = fullOptions.samplingMode;
  15055. texture.type = fullOptions.type;
  15056. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15057. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15058. // this.resetTextureCache();
  15059. this._internalTexturesCache.push(texture);
  15060. return texture;
  15061. };
  15062. /**
  15063. * Create a multi render target texture
  15064. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15065. * @param size defines the size of the texture
  15066. * @param options defines the creation options
  15067. * @returns the cube texture as an InternalTexture
  15068. */
  15069. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15070. var generateMipMaps = false;
  15071. var generateDepthBuffer = true;
  15072. var generateStencilBuffer = false;
  15073. var generateDepthTexture = false;
  15074. var textureCount = 1;
  15075. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15076. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15077. var types = new Array();
  15078. var samplingModes = new Array();
  15079. if (options !== undefined) {
  15080. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15081. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15082. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15083. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15084. textureCount = options.textureCount || 1;
  15085. if (options.types) {
  15086. types = options.types;
  15087. }
  15088. if (options.samplingModes) {
  15089. samplingModes = options.samplingModes;
  15090. }
  15091. }
  15092. var gl = this._gl;
  15093. // Create the framebuffer
  15094. var framebuffer = gl.createFramebuffer();
  15095. this.bindUnboundFramebuffer(framebuffer);
  15096. var width = size.width || size;
  15097. var height = size.height || size;
  15098. var textures = [];
  15099. var attachments = [];
  15100. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15101. for (var i = 0; i < textureCount; i++) {
  15102. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15103. var type = types[i] || defaultType;
  15104. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15105. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15106. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15107. }
  15108. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15109. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15110. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15111. }
  15112. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15113. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15114. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15115. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15116. }
  15117. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15118. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15119. textures.push(texture);
  15120. attachments.push(attachment);
  15121. gl.activeTexture(gl["TEXTURE" + i]);
  15122. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15127. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15128. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15129. if (generateMipMaps) {
  15130. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15131. }
  15132. // Unbind
  15133. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15134. texture._framebuffer = framebuffer;
  15135. texture._depthStencilBuffer = depthStencilBuffer;
  15136. texture.baseWidth = width;
  15137. texture.baseHeight = height;
  15138. texture.width = width;
  15139. texture.height = height;
  15140. texture.isReady = true;
  15141. texture.samples = 1;
  15142. texture.generateMipMaps = generateMipMaps;
  15143. texture.samplingMode = samplingMode;
  15144. texture.type = type;
  15145. texture._generateDepthBuffer = generateDepthBuffer;
  15146. texture._generateStencilBuffer = generateStencilBuffer;
  15147. texture._attachments = attachments;
  15148. this._internalTexturesCache.push(texture);
  15149. }
  15150. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15151. // Depth texture
  15152. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15153. gl.activeTexture(gl.TEXTURE0);
  15154. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15156. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15158. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15159. 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);
  15160. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15161. depthTexture._framebuffer = framebuffer;
  15162. depthTexture.baseWidth = width;
  15163. depthTexture.baseHeight = height;
  15164. depthTexture.width = width;
  15165. depthTexture.height = height;
  15166. depthTexture.isReady = true;
  15167. depthTexture.samples = 1;
  15168. depthTexture.generateMipMaps = generateMipMaps;
  15169. depthTexture.samplingMode = gl.NEAREST;
  15170. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15171. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15172. textures.push(depthTexture);
  15173. this._internalTexturesCache.push(depthTexture);
  15174. }
  15175. gl.drawBuffers(attachments);
  15176. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15177. this.bindUnboundFramebuffer(null);
  15178. this.resetTextureCache();
  15179. return textures;
  15180. };
  15181. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15182. if (samples === void 0) { samples = 1; }
  15183. var depthStencilBuffer = null;
  15184. var gl = this._gl;
  15185. // Create the depth/stencil buffer
  15186. if (generateStencilBuffer) {
  15187. depthStencilBuffer = gl.createRenderbuffer();
  15188. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15189. if (samples > 1) {
  15190. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15191. }
  15192. else {
  15193. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15194. }
  15195. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15196. }
  15197. else if (generateDepthBuffer) {
  15198. depthStencilBuffer = gl.createRenderbuffer();
  15199. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15200. if (samples > 1) {
  15201. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15202. }
  15203. else {
  15204. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15205. }
  15206. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15207. }
  15208. return depthStencilBuffer;
  15209. };
  15210. /**
  15211. * Updates the sample count of a render target texture
  15212. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15213. * @param texture defines the texture to update
  15214. * @param samples defines the sample count to set
  15215. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15216. */
  15217. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15218. if (this.webGLVersion < 2 || !texture) {
  15219. return 1;
  15220. }
  15221. if (texture.samples === samples) {
  15222. return samples;
  15223. }
  15224. var gl = this._gl;
  15225. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15226. // Dispose previous render buffers
  15227. if (texture._depthStencilBuffer) {
  15228. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15229. texture._depthStencilBuffer = null;
  15230. }
  15231. if (texture._MSAAFramebuffer) {
  15232. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15233. texture._MSAAFramebuffer = null;
  15234. }
  15235. if (texture._MSAARenderBuffer) {
  15236. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15237. texture._MSAARenderBuffer = null;
  15238. }
  15239. if (samples > 1) {
  15240. var framebuffer = gl.createFramebuffer();
  15241. if (!framebuffer) {
  15242. throw new Error("Unable to create multi sampled framebuffer");
  15243. }
  15244. texture._MSAAFramebuffer = framebuffer;
  15245. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15246. var colorRenderbuffer = gl.createRenderbuffer();
  15247. if (!colorRenderbuffer) {
  15248. throw new Error("Unable to create multi sampled framebuffer");
  15249. }
  15250. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15251. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15252. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15253. texture._MSAARenderBuffer = colorRenderbuffer;
  15254. }
  15255. else {
  15256. this.bindUnboundFramebuffer(texture._framebuffer);
  15257. }
  15258. texture.samples = samples;
  15259. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15260. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15261. this.bindUnboundFramebuffer(null);
  15262. return samples;
  15263. };
  15264. /**
  15265. * Update the sample count for a given multiple render target texture
  15266. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15267. * @param textures defines the textures to update
  15268. * @param samples defines the sample count to set
  15269. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15270. */
  15271. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15272. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15273. return 1;
  15274. }
  15275. if (textures[0].samples === samples) {
  15276. return samples;
  15277. }
  15278. var gl = this._gl;
  15279. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15280. // Dispose previous render buffers
  15281. if (textures[0]._depthStencilBuffer) {
  15282. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15283. textures[0]._depthStencilBuffer = null;
  15284. }
  15285. if (textures[0]._MSAAFramebuffer) {
  15286. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15287. textures[0]._MSAAFramebuffer = null;
  15288. }
  15289. for (var i = 0; i < textures.length; i++) {
  15290. if (textures[i]._MSAARenderBuffer) {
  15291. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15292. textures[i]._MSAARenderBuffer = null;
  15293. }
  15294. }
  15295. if (samples > 1) {
  15296. var framebuffer = gl.createFramebuffer();
  15297. if (!framebuffer) {
  15298. throw new Error("Unable to create multi sampled framebuffer");
  15299. }
  15300. this.bindUnboundFramebuffer(framebuffer);
  15301. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15302. var attachments = [];
  15303. for (var i = 0; i < textures.length; i++) {
  15304. var texture = textures[i];
  15305. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15306. var colorRenderbuffer = gl.createRenderbuffer();
  15307. if (!colorRenderbuffer) {
  15308. throw new Error("Unable to create multi sampled framebuffer");
  15309. }
  15310. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15311. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15312. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15313. texture._MSAAFramebuffer = framebuffer;
  15314. texture._MSAARenderBuffer = colorRenderbuffer;
  15315. texture.samples = samples;
  15316. texture._depthStencilBuffer = depthStencilBuffer;
  15317. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15318. attachments.push(attachment);
  15319. }
  15320. gl.drawBuffers(attachments);
  15321. }
  15322. else {
  15323. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15324. }
  15325. this.bindUnboundFramebuffer(null);
  15326. return samples;
  15327. };
  15328. /** @hidden */
  15329. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15330. if (faceIndex === void 0) { faceIndex = 0; }
  15331. if (lod === void 0) { lod = 0; }
  15332. var gl = this._gl;
  15333. var target = gl.TEXTURE_2D;
  15334. if (texture.isCube) {
  15335. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15336. }
  15337. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15338. };
  15339. /** @hidden */
  15340. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15341. if (faceIndex === void 0) { faceIndex = 0; }
  15342. if (lod === void 0) { lod = 0; }
  15343. var gl = this._gl;
  15344. var textureType = this._getWebGLTextureType(texture.type);
  15345. var format = this._getInternalFormat(texture.format);
  15346. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15347. this._unpackFlipY(texture.invertY);
  15348. var target = gl.TEXTURE_2D;
  15349. if (texture.isCube) {
  15350. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15351. }
  15352. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15353. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15354. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15355. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15356. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15357. };
  15358. /** @hidden */
  15359. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15360. if (faceIndex === void 0) { faceIndex = 0; }
  15361. if (lod === void 0) { lod = 0; }
  15362. var gl = this._gl;
  15363. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15364. this._bindTextureDirectly(bindTarget, texture, true);
  15365. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15366. this._bindTextureDirectly(bindTarget, null, true);
  15367. };
  15368. /** @hidden */
  15369. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15370. if (faceIndex === void 0) { faceIndex = 0; }
  15371. if (lod === void 0) { lod = 0; }
  15372. var gl = this._gl;
  15373. var textureType = this._getWebGLTextureType(texture.type);
  15374. var format = this._getInternalFormat(texture.format);
  15375. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15376. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15377. this._bindTextureDirectly(bindTarget, texture, true);
  15378. this._unpackFlipY(texture.invertY);
  15379. var target = gl.TEXTURE_2D;
  15380. if (texture.isCube) {
  15381. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15382. }
  15383. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15384. this._bindTextureDirectly(bindTarget, null, true);
  15385. };
  15386. /**
  15387. * Creates a new render target cube texture
  15388. * @param size defines the size of the texture
  15389. * @param options defines the options used to create the texture
  15390. * @returns a new render target cube texture stored in an InternalTexture
  15391. */
  15392. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15393. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15394. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15395. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15396. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15397. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15398. }
  15399. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15400. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15401. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15402. }
  15403. var gl = this._gl;
  15404. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15405. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15406. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15407. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15408. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15409. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15410. }
  15411. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15412. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15415. for (var face = 0; face < 6; face++) {
  15416. 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);
  15417. }
  15418. // Create the framebuffer
  15419. var framebuffer = gl.createFramebuffer();
  15420. this.bindUnboundFramebuffer(framebuffer);
  15421. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15422. // MipMaps
  15423. if (fullOptions.generateMipMaps) {
  15424. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15425. }
  15426. // Unbind
  15427. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15428. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15429. this.bindUnboundFramebuffer(null);
  15430. texture._framebuffer = framebuffer;
  15431. texture.width = size;
  15432. texture.height = size;
  15433. texture.isReady = true;
  15434. texture.isCube = true;
  15435. texture.samples = 1;
  15436. texture.generateMipMaps = fullOptions.generateMipMaps;
  15437. texture.samplingMode = fullOptions.samplingMode;
  15438. texture.type = fullOptions.type;
  15439. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15440. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15441. this._internalTexturesCache.push(texture);
  15442. return texture;
  15443. };
  15444. /**
  15445. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15446. * @param rootUrl defines the url where the file to load is located
  15447. * @param scene defines the current scene
  15448. * @param lodScale defines scale to apply to the mip map selection
  15449. * @param lodOffset defines offset to apply to the mip map selection
  15450. * @param onLoad defines an optional callback raised when the texture is loaded
  15451. * @param onError defines an optional callback raised if there is an issue to load the texture
  15452. * @param format defines the format of the data
  15453. * @param forcedExtension defines the extension to use to pick the right loader
  15454. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15455. * @returns the cube texture as an InternalTexture
  15456. */
  15457. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15458. var _this = this;
  15459. if (onLoad === void 0) { onLoad = null; }
  15460. if (onError === void 0) { onError = null; }
  15461. if (forcedExtension === void 0) { forcedExtension = null; }
  15462. if (createPolynomials === void 0) { createPolynomials = true; }
  15463. var callback = function (loadData) {
  15464. if (!loadData) {
  15465. if (onLoad) {
  15466. onLoad(null);
  15467. }
  15468. return;
  15469. }
  15470. var texture = loadData.texture;
  15471. if (!createPolynomials) {
  15472. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15473. }
  15474. else if (loadData.info.sphericalPolynomial) {
  15475. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15476. }
  15477. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15478. if (_this._caps.textureLOD) {
  15479. // Do not add extra process if texture lod is supported.
  15480. if (onLoad) {
  15481. onLoad(texture);
  15482. }
  15483. return;
  15484. }
  15485. var mipSlices = 3;
  15486. var gl = _this._gl;
  15487. var width = loadData.width;
  15488. if (!width) {
  15489. return;
  15490. }
  15491. var textures = [];
  15492. for (var i = 0; i < mipSlices; i++) {
  15493. //compute LOD from even spacing in smoothness (matching shader calculation)
  15494. var smoothness = i / (mipSlices - 1);
  15495. var roughness = 1 - smoothness;
  15496. var minLODIndex = lodOffset; // roughness = 0
  15497. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15498. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15499. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15500. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15501. glTextureFromLod.isCube = true;
  15502. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15507. if (loadData.isDDS) {
  15508. var info = loadData.info;
  15509. var data = loadData.data;
  15510. _this._unpackFlipY(info.isCompressed);
  15511. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, true, 6, mipmapIndex);
  15512. }
  15513. else {
  15514. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15515. }
  15516. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15517. // Wrap in a base texture for easy binding.
  15518. var lodTexture = new BABYLON.BaseTexture(scene);
  15519. lodTexture.isCube = true;
  15520. lodTexture._texture = glTextureFromLod;
  15521. glTextureFromLod.isReady = true;
  15522. textures.push(lodTexture);
  15523. }
  15524. texture._lodTextureHigh = textures[2];
  15525. texture._lodTextureMid = textures[1];
  15526. texture._lodTextureLow = textures[0];
  15527. if (onLoad) {
  15528. onLoad(texture);
  15529. }
  15530. };
  15531. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15532. };
  15533. /**
  15534. * Creates a cube texture
  15535. * @param rootUrl defines the url where the files to load is located
  15536. * @param scene defines the current scene
  15537. * @param files defines the list of files to load (1 per face)
  15538. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15539. * @param onLoad defines an optional callback raised when the texture is loaded
  15540. * @param onError defines an optional callback raised if there is an issue to load the texture
  15541. * @param format defines the format of the data
  15542. * @param forcedExtension defines the extension to use to pick the right loader
  15543. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15544. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15545. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15546. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15547. * @returns the cube texture as an InternalTexture
  15548. */
  15549. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15550. var _this = this;
  15551. if (onLoad === void 0) { onLoad = null; }
  15552. if (onError === void 0) { onError = null; }
  15553. if (forcedExtension === void 0) { forcedExtension = null; }
  15554. if (createPolynomials === void 0) { createPolynomials = false; }
  15555. if (lodScale === void 0) { lodScale = 0; }
  15556. if (lodOffset === void 0) { lodOffset = 0; }
  15557. if (fallback === void 0) { fallback = null; }
  15558. var gl = this._gl;
  15559. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15560. texture.isCube = true;
  15561. texture.url = rootUrl;
  15562. texture.generateMipMaps = !noMipmap;
  15563. texture._lodGenerationScale = lodScale;
  15564. texture._lodGenerationOffset = lodOffset;
  15565. if (!this._doNotHandleContextLost) {
  15566. texture._extension = forcedExtension;
  15567. texture._files = files;
  15568. }
  15569. var lastDot = rootUrl.lastIndexOf('.');
  15570. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15571. var loader = null;
  15572. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15573. var availableLoader = _a[_i];
  15574. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15575. loader = availableLoader;
  15576. break;
  15577. }
  15578. }
  15579. var onInternalError = function (request, exception) {
  15580. if (loader) {
  15581. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15582. if (fallbackUrl) {
  15583. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15584. }
  15585. }
  15586. if (onError && request) {
  15587. onError(request.status + " " + request.statusText, exception);
  15588. }
  15589. };
  15590. if (loader) {
  15591. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15592. var onloaddata = function (data) {
  15593. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15594. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15595. };
  15596. if (files && files.length === 6) {
  15597. if (loader.supportCascades) {
  15598. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15599. }
  15600. else if (onError) {
  15601. onError("Textures type does not support cascades.");
  15602. }
  15603. }
  15604. else {
  15605. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15606. }
  15607. }
  15608. else {
  15609. if (!files) {
  15610. throw new Error("Cannot load cubemap because files were not defined");
  15611. }
  15612. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15613. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15614. var height = width;
  15615. _this._prepareWorkingCanvas();
  15616. if (!_this._workingCanvas || !_this._workingContext) {
  15617. return;
  15618. }
  15619. _this._workingCanvas.width = width;
  15620. _this._workingCanvas.height = height;
  15621. var faces = [
  15622. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15623. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15624. ];
  15625. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15626. _this._unpackFlipY(false);
  15627. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15628. for (var index = 0; index < faces.length; index++) {
  15629. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15630. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15631. }
  15632. if (!noMipmap) {
  15633. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15634. }
  15635. _this._setCubeMapTextureParams(!noMipmap);
  15636. texture.width = width;
  15637. texture.height = height;
  15638. texture.isReady = true;
  15639. if (format) {
  15640. texture.format = format;
  15641. }
  15642. texture.onLoadedObservable.notifyObservers(texture);
  15643. texture.onLoadedObservable.clear();
  15644. if (onLoad) {
  15645. onLoad();
  15646. }
  15647. }, files, onError);
  15648. }
  15649. this._internalTexturesCache.push(texture);
  15650. return texture;
  15651. };
  15652. /**
  15653. * @hidden
  15654. */
  15655. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15656. var gl = this._gl;
  15657. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15658. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15659. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15660. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15661. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15662. // this.resetTextureCache();
  15663. };
  15664. /**
  15665. * Update a raw cube texture
  15666. * @param texture defines the texture to udpdate
  15667. * @param data defines the data to store
  15668. * @param format defines the data format
  15669. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15670. * @param invertY defines if data must be stored with Y axis inverted
  15671. * @param compression defines the compression used (null by default)
  15672. * @param level defines which level of the texture to update
  15673. */
  15674. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15675. if (compression === void 0) { compression = null; }
  15676. if (level === void 0) { level = 0; }
  15677. texture._bufferViewArray = data;
  15678. texture.format = format;
  15679. texture.type = type;
  15680. texture.invertY = invertY;
  15681. texture._compression = compression;
  15682. var gl = this._gl;
  15683. var textureType = this._getWebGLTextureType(type);
  15684. var internalFormat = this._getInternalFormat(format);
  15685. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15686. var needConversion = false;
  15687. if (internalFormat === gl.RGB) {
  15688. internalFormat = gl.RGBA;
  15689. needConversion = true;
  15690. }
  15691. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15692. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15693. if (texture.width % 4 !== 0) {
  15694. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15695. }
  15696. // Data are known to be in +X +Y +Z -X -Y -Z
  15697. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15698. var faceData = data[faceIndex];
  15699. if (compression) {
  15700. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15701. }
  15702. else {
  15703. if (needConversion) {
  15704. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15705. }
  15706. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15707. }
  15708. }
  15709. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15710. if (isPot && texture.generateMipMaps && level === 0) {
  15711. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15712. }
  15713. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15714. // this.resetTextureCache();
  15715. texture.isReady = true;
  15716. };
  15717. /**
  15718. * Creates a new raw cube texture
  15719. * @param data defines the array of data to use to create each face
  15720. * @param size defines the size of the textures
  15721. * @param format defines the format of the data
  15722. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15723. * @param generateMipMaps defines if the engine should generate the mip levels
  15724. * @param invertY defines if data must be stored with Y axis inverted
  15725. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15726. * @param compression defines the compression used (null by default)
  15727. * @returns the cube texture as an InternalTexture
  15728. */
  15729. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15730. if (compression === void 0) { compression = null; }
  15731. var gl = this._gl;
  15732. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15733. texture.isCube = true;
  15734. texture.generateMipMaps = generateMipMaps;
  15735. texture.format = format;
  15736. texture.type = type;
  15737. if (!this._doNotHandleContextLost) {
  15738. texture._bufferViewArray = data;
  15739. }
  15740. var textureType = this._getWebGLTextureType(type);
  15741. var internalFormat = this._getInternalFormat(format);
  15742. if (internalFormat === gl.RGB) {
  15743. internalFormat = gl.RGBA;
  15744. }
  15745. var width = size;
  15746. var height = width;
  15747. texture.width = width;
  15748. texture.height = height;
  15749. // Double check on POT to generate Mips.
  15750. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15751. if (!isPot) {
  15752. generateMipMaps = false;
  15753. }
  15754. // Upload data if needed. The texture won't be ready until then.
  15755. if (data) {
  15756. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15757. }
  15758. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15759. // Filters
  15760. if (data && generateMipMaps) {
  15761. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15762. }
  15763. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15766. }
  15767. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15770. }
  15771. else {
  15772. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15775. }
  15776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15778. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15779. return texture;
  15780. };
  15781. /**
  15782. * Creates a new raw cube texture from a specified url
  15783. * @param url defines the url where the data is located
  15784. * @param scene defines the current scene
  15785. * @param size defines the size of the textures
  15786. * @param format defines the format of the data
  15787. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15788. * @param noMipmap defines if the engine should avoid generating the mip levels
  15789. * @param callback defines a callback used to extract texture data from loaded data
  15790. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15791. * @param onLoad defines a callback called when texture is loaded
  15792. * @param onError defines a callback called if there is an error
  15793. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15794. * @param invertY defines if data must be stored with Y axis inverted
  15795. * @returns the cube texture as an InternalTexture
  15796. */
  15797. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15798. var _this = this;
  15799. if (onLoad === void 0) { onLoad = null; }
  15800. if (onError === void 0) { onError = null; }
  15801. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15802. if (invertY === void 0) { invertY = false; }
  15803. var gl = this._gl;
  15804. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15805. scene._addPendingData(texture);
  15806. texture.url = url;
  15807. this._internalTexturesCache.push(texture);
  15808. var onerror = function (request, exception) {
  15809. scene._removePendingData(texture);
  15810. if (onError && request) {
  15811. onError(request.status + " " + request.statusText, exception);
  15812. }
  15813. };
  15814. var internalCallback = function (data) {
  15815. var width = texture.width;
  15816. var faceDataArrays = callback(data);
  15817. if (!faceDataArrays) {
  15818. return;
  15819. }
  15820. if (mipmapGenerator) {
  15821. var textureType = _this._getWebGLTextureType(type);
  15822. var internalFormat = _this._getInternalFormat(format);
  15823. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15824. var needConversion = false;
  15825. if (internalFormat === gl.RGB) {
  15826. internalFormat = gl.RGBA;
  15827. needConversion = true;
  15828. }
  15829. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15830. _this._unpackFlipY(false);
  15831. var mipData = mipmapGenerator(faceDataArrays);
  15832. for (var level = 0; level < mipData.length; level++) {
  15833. var mipSize = width >> level;
  15834. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15835. var mipFaceData = mipData[level][faceIndex];
  15836. if (needConversion) {
  15837. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15838. }
  15839. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15840. }
  15841. }
  15842. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15843. }
  15844. else {
  15845. texture.generateMipMaps = !noMipmap;
  15846. if (type === Engine.TEXTURETYPE_FLOAT && !_this._caps.textureFloatLinearFiltering) {
  15847. texture.generateMipMaps = false;
  15848. }
  15849. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15850. }
  15851. texture.isReady = true;
  15852. // this.resetTextureCache();
  15853. scene._removePendingData(texture);
  15854. if (onLoad) {
  15855. onLoad();
  15856. }
  15857. };
  15858. this._loadFile(url, function (data) {
  15859. internalCallback(data);
  15860. }, undefined, scene.database, true, onerror);
  15861. return texture;
  15862. };
  15863. ;
  15864. /**
  15865. * Update a raw 3D texture
  15866. * @param texture defines the texture to update
  15867. * @param data defines the data to store
  15868. * @param format defines the data format
  15869. * @param invertY defines if data must be stored with Y axis inverted
  15870. * @param compression defines the used compression (can be null)
  15871. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15872. */
  15873. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15874. if (compression === void 0) { compression = null; }
  15875. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15876. var internalType = this._getWebGLTextureType(textureType);
  15877. var internalFormat = this._getInternalFormat(format);
  15878. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15879. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15880. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15881. if (!this._doNotHandleContextLost) {
  15882. texture._bufferView = data;
  15883. texture.format = format;
  15884. texture.invertY = invertY;
  15885. texture._compression = compression;
  15886. }
  15887. if (texture.width % 4 !== 0) {
  15888. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15889. }
  15890. if (compression && data) {
  15891. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15892. }
  15893. else {
  15894. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15895. }
  15896. if (texture.generateMipMaps) {
  15897. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15898. }
  15899. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15900. // this.resetTextureCache();
  15901. texture.isReady = true;
  15902. };
  15903. /**
  15904. * Creates a new raw 3D texture
  15905. * @param data defines the data used to create the texture
  15906. * @param width defines the width of the texture
  15907. * @param height defines the height of the texture
  15908. * @param depth defines the depth of the texture
  15909. * @param format defines the format of the texture
  15910. * @param generateMipMaps defines if the engine must generate mip levels
  15911. * @param invertY defines if data must be stored with Y axis inverted
  15912. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15913. * @param compression defines the compressed used (can be null)
  15914. * @param textureType defines the compressed used (can be null)
  15915. * @returns a new raw 3D texture (stored in an InternalTexture)
  15916. */
  15917. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15918. if (compression === void 0) { compression = null; }
  15919. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15921. texture.baseWidth = width;
  15922. texture.baseHeight = height;
  15923. texture.baseDepth = depth;
  15924. texture.width = width;
  15925. texture.height = height;
  15926. texture.depth = depth;
  15927. texture.format = format;
  15928. texture.type = textureType;
  15929. texture.generateMipMaps = generateMipMaps;
  15930. texture.samplingMode = samplingMode;
  15931. texture.is3D = true;
  15932. if (!this._doNotHandleContextLost) {
  15933. texture._bufferView = data;
  15934. }
  15935. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15936. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15937. // Filters
  15938. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15939. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15940. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15941. if (generateMipMaps) {
  15942. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15943. }
  15944. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15945. this._internalTexturesCache.push(texture);
  15946. return texture;
  15947. };
  15948. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15949. var gl = this._gl;
  15950. if (!gl) {
  15951. return;
  15952. }
  15953. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15954. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15955. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15956. if (!noMipmap && !isCompressed) {
  15957. gl.generateMipmap(gl.TEXTURE_2D);
  15958. }
  15959. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15960. // this.resetTextureCache();
  15961. if (scene) {
  15962. scene._removePendingData(texture);
  15963. }
  15964. texture.onLoadedObservable.notifyObservers(texture);
  15965. texture.onLoadedObservable.clear();
  15966. };
  15967. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15968. var _this = this;
  15969. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15970. var maxTextureSize = this.getCaps().maxTextureSize;
  15971. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  15972. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  15973. var gl = this._gl;
  15974. if (!gl) {
  15975. return;
  15976. }
  15977. if (!texture._webGLTexture) {
  15978. // this.resetTextureCache();
  15979. if (scene) {
  15980. scene._removePendingData(texture);
  15981. }
  15982. return;
  15983. }
  15984. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15985. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15986. texture.baseWidth = width;
  15987. texture.baseHeight = height;
  15988. texture.width = potWidth;
  15989. texture.height = potHeight;
  15990. texture.isReady = true;
  15991. if (processFunction(potWidth, potHeight, function () {
  15992. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15993. })) {
  15994. // Returning as texture needs extra async steps
  15995. return;
  15996. }
  15997. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15998. };
  15999. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16000. // Create new RGBA data container.
  16001. var rgbaData;
  16002. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16003. rgbaData = new Float32Array(width * height * 4);
  16004. }
  16005. else {
  16006. rgbaData = new Uint32Array(width * height * 4);
  16007. }
  16008. // Convert each pixel.
  16009. for (var x = 0; x < width; x++) {
  16010. for (var y = 0; y < height; y++) {
  16011. var index = (y * width + x) * 3;
  16012. var newIndex = (y * width + x) * 4;
  16013. // Map Old Value to new value.
  16014. rgbaData[newIndex + 0] = rgbData[index + 0];
  16015. rgbaData[newIndex + 1] = rgbData[index + 1];
  16016. rgbaData[newIndex + 2] = rgbData[index + 2];
  16017. // Add fully opaque alpha channel.
  16018. rgbaData[newIndex + 3] = 1;
  16019. }
  16020. }
  16021. return rgbaData;
  16022. };
  16023. /** @hidden */
  16024. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16025. var gl = this._gl;
  16026. if (texture._framebuffer) {
  16027. gl.deleteFramebuffer(texture._framebuffer);
  16028. texture._framebuffer = null;
  16029. }
  16030. if (texture._depthStencilBuffer) {
  16031. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16032. texture._depthStencilBuffer = null;
  16033. }
  16034. if (texture._MSAAFramebuffer) {
  16035. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16036. texture._MSAAFramebuffer = null;
  16037. }
  16038. if (texture._MSAARenderBuffer) {
  16039. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16040. texture._MSAARenderBuffer = null;
  16041. }
  16042. };
  16043. /** @hidden */
  16044. Engine.prototype._releaseTexture = function (texture) {
  16045. var gl = this._gl;
  16046. this._releaseFramebufferObjects(texture);
  16047. gl.deleteTexture(texture._webGLTexture);
  16048. // Unbind channels
  16049. this.unbindAllTextures();
  16050. var index = this._internalTexturesCache.indexOf(texture);
  16051. if (index !== -1) {
  16052. this._internalTexturesCache.splice(index, 1);
  16053. }
  16054. // Integrated fixed lod samplers.
  16055. if (texture._lodTextureHigh) {
  16056. texture._lodTextureHigh.dispose();
  16057. }
  16058. if (texture._lodTextureMid) {
  16059. texture._lodTextureMid.dispose();
  16060. }
  16061. if (texture._lodTextureLow) {
  16062. texture._lodTextureLow.dispose();
  16063. }
  16064. // Set output texture of post process to null if the texture has been released/disposed
  16065. this.scenes.forEach(function (scene) {
  16066. scene.postProcesses.forEach(function (postProcess) {
  16067. if (postProcess._outputTexture == texture) {
  16068. postProcess._outputTexture = null;
  16069. }
  16070. });
  16071. scene.cameras.forEach(function (camera) {
  16072. camera._postProcesses.forEach(function (postProcess) {
  16073. if (postProcess) {
  16074. if (postProcess._outputTexture == texture) {
  16075. postProcess._outputTexture = null;
  16076. }
  16077. }
  16078. });
  16079. });
  16080. });
  16081. };
  16082. Engine.prototype.setProgram = function (program) {
  16083. if (this._currentProgram !== program) {
  16084. this._gl.useProgram(program);
  16085. this._currentProgram = program;
  16086. }
  16087. };
  16088. /**
  16089. * Binds an effect to the webGL context
  16090. * @param effect defines the effect to bind
  16091. */
  16092. Engine.prototype.bindSamplers = function (effect) {
  16093. this.setProgram(effect.getProgram());
  16094. var samplers = effect.getSamplers();
  16095. for (var index = 0; index < samplers.length; index++) {
  16096. var uniform = effect.getUniform(samplers[index]);
  16097. if (uniform) {
  16098. this._boundUniforms[index] = uniform;
  16099. }
  16100. }
  16101. this._currentEffect = null;
  16102. };
  16103. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16104. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16105. return;
  16106. }
  16107. // Remove
  16108. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16109. // Bind last to it
  16110. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16111. // Bind to dummy
  16112. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16113. };
  16114. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16115. if (!internalTexture) {
  16116. return -1;
  16117. }
  16118. internalTexture._initialSlot = channel;
  16119. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16120. if (channel !== internalTexture._designatedSlot) {
  16121. this._textureCollisions.addCount(1, false);
  16122. }
  16123. }
  16124. else {
  16125. if (channel !== internalTexture._designatedSlot) {
  16126. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16127. return internalTexture._designatedSlot;
  16128. }
  16129. else {
  16130. // No slot for this texture, let's pick a new one (if we find a free slot)
  16131. if (this._nextFreeTextureSlots.length) {
  16132. return this._nextFreeTextureSlots[0];
  16133. }
  16134. // We need to recycle the oldest bound texture, sorry.
  16135. this._textureCollisions.addCount(1, false);
  16136. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16137. }
  16138. }
  16139. }
  16140. return channel;
  16141. };
  16142. Engine.prototype._linkTrackers = function (previous, next) {
  16143. previous.next = next;
  16144. next.previous = previous;
  16145. };
  16146. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16147. var currentSlot = internalTexture._designatedSlot;
  16148. if (currentSlot === -1) {
  16149. return -1;
  16150. }
  16151. internalTexture._designatedSlot = -1;
  16152. if (this.disableTextureBindingOptimization) {
  16153. return -1;
  16154. }
  16155. // Remove from bound list
  16156. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16157. // Free the slot
  16158. this._boundTexturesCache[currentSlot] = null;
  16159. this._nextFreeTextureSlots.push(currentSlot);
  16160. return currentSlot;
  16161. };
  16162. Engine.prototype._activateCurrentTexture = function () {
  16163. if (this._currentTextureChannel !== this._activeChannel) {
  16164. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16165. this._currentTextureChannel = this._activeChannel;
  16166. }
  16167. };
  16168. /** @hidden */
  16169. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16170. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16171. if (force === void 0) { force = false; }
  16172. var wasPreviouslyBound = false;
  16173. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16174. this._activeChannel = texture._designatedSlot;
  16175. }
  16176. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16177. var isTextureForRendering = texture && texture._initialSlot > -1;
  16178. if (currentTextureBound !== texture || force) {
  16179. if (currentTextureBound) {
  16180. this._removeDesignatedSlot(currentTextureBound);
  16181. }
  16182. this._activateCurrentTexture();
  16183. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16184. this._boundTexturesCache[this._activeChannel] = texture;
  16185. if (texture) {
  16186. if (!this.disableTextureBindingOptimization) {
  16187. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16188. if (slotIndex > -1) {
  16189. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16190. }
  16191. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16192. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16193. }
  16194. texture._designatedSlot = this._activeChannel;
  16195. }
  16196. }
  16197. else if (forTextureDataUpdate) {
  16198. wasPreviouslyBound = true;
  16199. this._activateCurrentTexture();
  16200. }
  16201. if (isTextureForRendering && !forTextureDataUpdate) {
  16202. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16203. }
  16204. return wasPreviouslyBound;
  16205. };
  16206. /** @hidden */
  16207. Engine.prototype._bindTexture = function (channel, texture) {
  16208. if (channel < 0) {
  16209. return;
  16210. }
  16211. if (texture) {
  16212. channel = this._getCorrectTextureChannel(channel, texture);
  16213. }
  16214. this._activeChannel = channel;
  16215. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16216. };
  16217. /**
  16218. * Sets a texture to the webGL context from a postprocess
  16219. * @param channel defines the channel to use
  16220. * @param postProcess defines the source postprocess
  16221. */
  16222. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16223. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16224. };
  16225. /**
  16226. * Binds the output of the passed in post process to the texture channel specified
  16227. * @param channel The channel the texture should be bound to
  16228. * @param postProcess The post process which's output should be bound
  16229. */
  16230. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16231. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16232. };
  16233. /**
  16234. * Unbind all textures from the webGL context
  16235. */
  16236. Engine.prototype.unbindAllTextures = function () {
  16237. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16238. this._activeChannel = channel;
  16239. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16240. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16241. if (this.webGLVersion > 1) {
  16242. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16243. }
  16244. }
  16245. };
  16246. /**
  16247. * Sets a texture to the according uniform.
  16248. * @param channel The texture channel
  16249. * @param uniform The uniform to set
  16250. * @param texture The texture to apply
  16251. */
  16252. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16253. if (channel < 0) {
  16254. return;
  16255. }
  16256. if (uniform) {
  16257. this._boundUniforms[channel] = uniform;
  16258. }
  16259. this._setTexture(channel, texture);
  16260. };
  16261. /**
  16262. * Sets a depth stencil texture from a render target to the according uniform.
  16263. * @param channel The texture channel
  16264. * @param uniform The uniform to set
  16265. * @param texture The render target texture containing the depth stencil texture to apply
  16266. */
  16267. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16268. if (channel < 0) {
  16269. return;
  16270. }
  16271. if (uniform) {
  16272. this._boundUniforms[channel] = uniform;
  16273. }
  16274. if (!texture || !texture.depthStencilTexture) {
  16275. this._setTexture(channel, null);
  16276. }
  16277. else {
  16278. this._setTexture(channel, texture, false, true);
  16279. }
  16280. };
  16281. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16282. var uniform = this._boundUniforms[sourceSlot];
  16283. if (uniform._currentState === destination) {
  16284. return;
  16285. }
  16286. this._gl.uniform1i(uniform, destination);
  16287. uniform._currentState = destination;
  16288. };
  16289. Engine.prototype._getTextureWrapMode = function (mode) {
  16290. switch (mode) {
  16291. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16292. return this._gl.REPEAT;
  16293. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16294. return this._gl.CLAMP_TO_EDGE;
  16295. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16296. return this._gl.MIRRORED_REPEAT;
  16297. }
  16298. return this._gl.REPEAT;
  16299. };
  16300. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16301. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16302. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16303. // Not ready?
  16304. if (!texture) {
  16305. if (this._boundTexturesCache[channel] != null) {
  16306. this._activeChannel = channel;
  16307. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16308. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16309. if (this.webGLVersion > 1) {
  16310. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16311. }
  16312. }
  16313. return false;
  16314. }
  16315. // Video
  16316. if (texture.video) {
  16317. this._activeChannel = channel;
  16318. texture.update();
  16319. }
  16320. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16321. texture.delayLoad();
  16322. return false;
  16323. }
  16324. var internalTexture;
  16325. if (depthStencilTexture) {
  16326. internalTexture = texture.depthStencilTexture;
  16327. }
  16328. else if (texture.isReady()) {
  16329. internalTexture = texture.getInternalTexture();
  16330. }
  16331. else if (texture.isCube) {
  16332. internalTexture = this.emptyCubeTexture;
  16333. }
  16334. else if (texture.is3D) {
  16335. internalTexture = this.emptyTexture3D;
  16336. }
  16337. else {
  16338. internalTexture = this.emptyTexture;
  16339. }
  16340. if (!isPartOfTextureArray) {
  16341. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16342. }
  16343. var needToBind = true;
  16344. if (this._boundTexturesCache[channel] === internalTexture) {
  16345. this._moveBoundTextureOnTop(internalTexture);
  16346. if (!isPartOfTextureArray) {
  16347. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16348. }
  16349. needToBind = false;
  16350. }
  16351. this._activeChannel = channel;
  16352. if (internalTexture && internalTexture.is3D) {
  16353. if (needToBind) {
  16354. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16355. }
  16356. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16357. internalTexture._cachedWrapU = texture.wrapU;
  16358. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16359. }
  16360. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16361. internalTexture._cachedWrapV = texture.wrapV;
  16362. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16363. }
  16364. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16365. internalTexture._cachedWrapR = texture.wrapR;
  16366. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16367. }
  16368. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16369. }
  16370. else if (internalTexture && internalTexture.isCube) {
  16371. if (needToBind) {
  16372. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16373. }
  16374. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16375. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16376. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16377. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16378. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16379. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16380. }
  16381. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16382. }
  16383. else {
  16384. if (needToBind) {
  16385. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16386. }
  16387. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16388. internalTexture._cachedWrapU = texture.wrapU;
  16389. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16390. }
  16391. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16392. internalTexture._cachedWrapV = texture.wrapV;
  16393. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16394. }
  16395. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16396. }
  16397. return true;
  16398. };
  16399. /**
  16400. * Sets an array of texture to the webGL context
  16401. * @param channel defines the channel where the texture array must be set
  16402. * @param uniform defines the associated uniform location
  16403. * @param textures defines the array of textures to bind
  16404. */
  16405. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16406. if (channel < 0 || !uniform) {
  16407. return;
  16408. }
  16409. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16410. this._textureUnits = new Int32Array(textures.length);
  16411. }
  16412. for (var i = 0; i < textures.length; i++) {
  16413. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16414. }
  16415. this._gl.uniform1iv(uniform, this._textureUnits);
  16416. for (var index = 0; index < textures.length; index++) {
  16417. this._setTexture(this._textureUnits[index], textures[index], true);
  16418. }
  16419. };
  16420. /** @hidden */
  16421. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16422. var internalTexture = texture.getInternalTexture();
  16423. if (!internalTexture) {
  16424. return;
  16425. }
  16426. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16427. var value = texture.anisotropicFilteringLevel;
  16428. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16429. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16430. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16431. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16432. }
  16433. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16434. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16435. internalTexture._cachedAnisotropicFilteringLevel = value;
  16436. }
  16437. };
  16438. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16439. this._bindTextureDirectly(target, texture, true, true);
  16440. this._gl.texParameterf(target, parameter, value);
  16441. };
  16442. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16443. if (texture) {
  16444. this._bindTextureDirectly(target, texture, true, true);
  16445. }
  16446. this._gl.texParameteri(target, parameter, value);
  16447. };
  16448. /**
  16449. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16450. * @param x defines the x coordinate of the rectangle where pixels must be read
  16451. * @param y defines the y coordinate of the rectangle where pixels must be read
  16452. * @param width defines the width of the rectangle where pixels must be read
  16453. * @param height defines the height of the rectangle where pixels must be read
  16454. * @returns a Uint8Array containing RGBA colors
  16455. */
  16456. Engine.prototype.readPixels = function (x, y, width, height) {
  16457. var data = new Uint8Array(height * width * 4);
  16458. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16459. return data;
  16460. };
  16461. /**
  16462. * Add an externaly attached data from its key.
  16463. * This method call will fail and return false, if such key already exists.
  16464. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16465. * @param key the unique key that identifies the data
  16466. * @param data the data object to associate to the key for this Engine instance
  16467. * @return true if no such key were already present and the data was added successfully, false otherwise
  16468. */
  16469. Engine.prototype.addExternalData = function (key, data) {
  16470. if (!this._externalData) {
  16471. this._externalData = new BABYLON.StringDictionary();
  16472. }
  16473. return this._externalData.add(key, data);
  16474. };
  16475. /**
  16476. * Get an externaly attached data from its key
  16477. * @param key the unique key that identifies the data
  16478. * @return the associated data, if present (can be null), or undefined if not present
  16479. */
  16480. Engine.prototype.getExternalData = function (key) {
  16481. if (!this._externalData) {
  16482. this._externalData = new BABYLON.StringDictionary();
  16483. }
  16484. return this._externalData.get(key);
  16485. };
  16486. /**
  16487. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16488. * @param key the unique key that identifies the data
  16489. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16490. * @return the associated data, can be null if the factory returned null.
  16491. */
  16492. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16493. if (!this._externalData) {
  16494. this._externalData = new BABYLON.StringDictionary();
  16495. }
  16496. return this._externalData.getOrAddWithFactory(key, factory);
  16497. };
  16498. /**
  16499. * Remove an externaly attached data from the Engine instance
  16500. * @param key the unique key that identifies the data
  16501. * @return true if the data was successfully removed, false if it doesn't exist
  16502. */
  16503. Engine.prototype.removeExternalData = function (key) {
  16504. if (!this._externalData) {
  16505. this._externalData = new BABYLON.StringDictionary();
  16506. }
  16507. return this._externalData.remove(key);
  16508. };
  16509. /**
  16510. * Unbind all vertex attributes from the webGL context
  16511. */
  16512. Engine.prototype.unbindAllAttributes = function () {
  16513. if (this._mustWipeVertexAttributes) {
  16514. this._mustWipeVertexAttributes = false;
  16515. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16516. this._gl.disableVertexAttribArray(i);
  16517. this._vertexAttribArraysEnabled[i] = false;
  16518. this._currentBufferPointers[i].active = false;
  16519. }
  16520. return;
  16521. }
  16522. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16523. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16524. continue;
  16525. }
  16526. this._gl.disableVertexAttribArray(i);
  16527. this._vertexAttribArraysEnabled[i] = false;
  16528. this._currentBufferPointers[i].active = false;
  16529. }
  16530. };
  16531. /**
  16532. * 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
  16533. */
  16534. Engine.prototype.releaseEffects = function () {
  16535. for (var name in this._compiledEffects) {
  16536. this._deleteProgram(this._compiledEffects[name]._program);
  16537. }
  16538. this._compiledEffects = {};
  16539. };
  16540. /**
  16541. * Dispose and release all associated resources
  16542. */
  16543. Engine.prototype.dispose = function () {
  16544. this.hideLoadingUI();
  16545. this.stopRenderLoop();
  16546. // Release postProcesses
  16547. while (this.postProcesses.length) {
  16548. this.postProcesses[0].dispose();
  16549. }
  16550. // Empty texture
  16551. if (this._emptyTexture) {
  16552. this._releaseTexture(this._emptyTexture);
  16553. this._emptyTexture = null;
  16554. }
  16555. if (this._emptyCubeTexture) {
  16556. this._releaseTexture(this._emptyCubeTexture);
  16557. this._emptyCubeTexture = null;
  16558. }
  16559. // Rescale PP
  16560. if (this._rescalePostProcess) {
  16561. this._rescalePostProcess.dispose();
  16562. }
  16563. // Release scenes
  16564. while (this.scenes.length) {
  16565. this.scenes[0].dispose();
  16566. }
  16567. // Release audio engine
  16568. if (Engine.audioEngine) {
  16569. Engine.audioEngine.dispose();
  16570. }
  16571. // Release effects
  16572. this.releaseEffects();
  16573. // Unbind
  16574. this.unbindAllAttributes();
  16575. this._boundUniforms = [];
  16576. if (this._dummyFramebuffer) {
  16577. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16578. }
  16579. //WebVR
  16580. this.disableVR();
  16581. // Events
  16582. if (BABYLON.Tools.IsWindowObjectExist()) {
  16583. window.removeEventListener("blur", this._onBlur);
  16584. window.removeEventListener("focus", this._onFocus);
  16585. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16586. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16587. if (this._renderingCanvas) {
  16588. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16589. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16590. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16591. if (!this._doNotHandleContextLost) {
  16592. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16593. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16594. }
  16595. }
  16596. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16597. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16598. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16599. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16600. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16601. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16602. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16603. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16604. if (this._onVrDisplayConnect) {
  16605. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16606. if (this._onVrDisplayDisconnect) {
  16607. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16608. }
  16609. if (this._onVrDisplayPresentChange) {
  16610. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16611. }
  16612. this._onVrDisplayConnect = null;
  16613. this._onVrDisplayDisconnect = null;
  16614. }
  16615. }
  16616. // Remove from Instances
  16617. var index = Engine.Instances.indexOf(this);
  16618. if (index >= 0) {
  16619. Engine.Instances.splice(index, 1);
  16620. }
  16621. this._workingCanvas = null;
  16622. this._workingContext = null;
  16623. this._currentBufferPointers = [];
  16624. this._renderingCanvas = null;
  16625. this._currentProgram = null;
  16626. this._bindedRenderFunction = null;
  16627. this.onResizeObservable.clear();
  16628. this.onCanvasBlurObservable.clear();
  16629. this.onCanvasFocusObservable.clear();
  16630. this.onCanvasPointerOutObservable.clear();
  16631. this.onBeginFrameObservable.clear();
  16632. this.onEndFrameObservable.clear();
  16633. BABYLON.Effect.ResetCache();
  16634. // Abort active requests
  16635. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16636. var request = _a[_i];
  16637. request.abort();
  16638. }
  16639. };
  16640. // Loading screen
  16641. /**
  16642. * Display the loading screen
  16643. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16644. */
  16645. Engine.prototype.displayLoadingUI = function () {
  16646. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16647. return;
  16648. }
  16649. var loadingScreen = this.loadingScreen;
  16650. if (loadingScreen) {
  16651. loadingScreen.displayLoadingUI();
  16652. }
  16653. };
  16654. /**
  16655. * Hide the loading screen
  16656. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16657. */
  16658. Engine.prototype.hideLoadingUI = function () {
  16659. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16660. return;
  16661. }
  16662. var loadingScreen = this.loadingScreen;
  16663. if (loadingScreen) {
  16664. loadingScreen.hideLoadingUI();
  16665. }
  16666. };
  16667. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16668. /**
  16669. * Gets the current loading screen object
  16670. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16671. */
  16672. get: function () {
  16673. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16674. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16675. return this._loadingScreen;
  16676. },
  16677. /**
  16678. * Sets the current loading screen object
  16679. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16680. */
  16681. set: function (loadingScreen) {
  16682. this._loadingScreen = loadingScreen;
  16683. },
  16684. enumerable: true,
  16685. configurable: true
  16686. });
  16687. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16688. /**
  16689. * Sets the current loading screen text
  16690. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16691. */
  16692. set: function (text) {
  16693. this.loadingScreen.loadingUIText = text;
  16694. },
  16695. enumerable: true,
  16696. configurable: true
  16697. });
  16698. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16699. /**
  16700. * Sets the current loading screen background color
  16701. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16702. */
  16703. set: function (color) {
  16704. this.loadingScreen.loadingUIBackgroundColor = color;
  16705. },
  16706. enumerable: true,
  16707. configurable: true
  16708. });
  16709. /**
  16710. * Attach a new callback raised when context lost event is fired
  16711. * @param callback defines the callback to call
  16712. */
  16713. Engine.prototype.attachContextLostEvent = function (callback) {
  16714. if (this._renderingCanvas) {
  16715. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16716. }
  16717. };
  16718. /**
  16719. * Attach a new callback raised when context restored event is fired
  16720. * @param callback defines the callback to call
  16721. */
  16722. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16723. if (this._renderingCanvas) {
  16724. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16725. }
  16726. };
  16727. /**
  16728. * Gets the source code of the vertex shader associated with a specific webGL program
  16729. * @param program defines the program to use
  16730. * @returns a string containing the source code of the vertex shader associated with the program
  16731. */
  16732. Engine.prototype.getVertexShaderSource = function (program) {
  16733. var shaders = this._gl.getAttachedShaders(program);
  16734. if (!shaders) {
  16735. return null;
  16736. }
  16737. return this._gl.getShaderSource(shaders[0]);
  16738. };
  16739. /**
  16740. * Gets the source code of the fragment shader associated with a specific webGL program
  16741. * @param program defines the program to use
  16742. * @returns a string containing the source code of the fragment shader associated with the program
  16743. */
  16744. Engine.prototype.getFragmentShaderSource = function (program) {
  16745. var shaders = this._gl.getAttachedShaders(program);
  16746. if (!shaders) {
  16747. return null;
  16748. }
  16749. return this._gl.getShaderSource(shaders[1]);
  16750. };
  16751. /**
  16752. * Get the current error code of the webGL context
  16753. * @returns the error code
  16754. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16755. */
  16756. Engine.prototype.getError = function () {
  16757. return this._gl.getError();
  16758. };
  16759. // FPS
  16760. /**
  16761. * Gets the current framerate
  16762. * @returns a number representing the framerate
  16763. */
  16764. Engine.prototype.getFps = function () {
  16765. return this._fps;
  16766. };
  16767. /**
  16768. * Gets the time spent between current and previous frame
  16769. * @returns a number representing the delta time in ms
  16770. */
  16771. Engine.prototype.getDeltaTime = function () {
  16772. return this._deltaTime;
  16773. };
  16774. Engine.prototype._measureFps = function () {
  16775. this._performanceMonitor.sampleFrame();
  16776. this._fps = this._performanceMonitor.averageFPS;
  16777. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16778. };
  16779. /** @hidden */
  16780. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16781. if (faceIndex === void 0) { faceIndex = -1; }
  16782. if (level === void 0) { level = 0; }
  16783. var gl = this._gl;
  16784. if (!this._dummyFramebuffer) {
  16785. var dummy = gl.createFramebuffer();
  16786. if (!dummy) {
  16787. throw new Error("Unable to create dummy framebuffer");
  16788. }
  16789. this._dummyFramebuffer = dummy;
  16790. }
  16791. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16792. if (faceIndex > -1) {
  16793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16794. }
  16795. else {
  16796. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16797. }
  16798. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16799. var buffer;
  16800. switch (readType) {
  16801. case gl.UNSIGNED_BYTE:
  16802. buffer = new Uint8Array(4 * width * height);
  16803. readType = gl.UNSIGNED_BYTE;
  16804. break;
  16805. default:
  16806. buffer = new Float32Array(4 * width * height);
  16807. readType = gl.FLOAT;
  16808. break;
  16809. }
  16810. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16811. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16812. return buffer;
  16813. };
  16814. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16815. if (this._webGLVersion > 1) {
  16816. return this._caps.colorBufferFloat;
  16817. }
  16818. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16819. };
  16820. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16821. if (this._webGLVersion > 1) {
  16822. return this._caps.colorBufferFloat;
  16823. }
  16824. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16825. };
  16826. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16827. Engine.prototype._canRenderToFramebuffer = function (type) {
  16828. var gl = this._gl;
  16829. //clear existing errors
  16830. while (gl.getError() !== gl.NO_ERROR) { }
  16831. var successful = true;
  16832. var texture = gl.createTexture();
  16833. gl.bindTexture(gl.TEXTURE_2D, texture);
  16834. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16836. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16837. var fb = gl.createFramebuffer();
  16838. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16839. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16840. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16841. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16842. successful = successful && (gl.getError() === gl.NO_ERROR);
  16843. //try render by clearing frame buffer's color buffer
  16844. if (successful) {
  16845. gl.clear(gl.COLOR_BUFFER_BIT);
  16846. successful = successful && (gl.getError() === gl.NO_ERROR);
  16847. }
  16848. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16849. if (successful) {
  16850. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16851. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16852. var readFormat = gl.RGBA;
  16853. var readType = gl.UNSIGNED_BYTE;
  16854. var buffer = new Uint8Array(4);
  16855. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16856. successful = successful && (gl.getError() === gl.NO_ERROR);
  16857. }
  16858. //clean up
  16859. gl.deleteTexture(texture);
  16860. gl.deleteFramebuffer(fb);
  16861. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16862. //clear accumulated errors
  16863. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16864. return successful;
  16865. };
  16866. /** @hidden */
  16867. Engine.prototype._getWebGLTextureType = function (type) {
  16868. if (type === Engine.TEXTURETYPE_FLOAT) {
  16869. return this._gl.FLOAT;
  16870. }
  16871. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16872. // Add Half Float Constant.
  16873. return this._gl.HALF_FLOAT_OES;
  16874. }
  16875. return this._gl.UNSIGNED_BYTE;
  16876. };
  16877. ;
  16878. Engine.prototype._getInternalFormat = function (format) {
  16879. var internalFormat = this._gl.RGBA;
  16880. switch (format) {
  16881. case Engine.TEXTUREFORMAT_ALPHA:
  16882. internalFormat = this._gl.ALPHA;
  16883. break;
  16884. case Engine.TEXTUREFORMAT_LUMINANCE:
  16885. internalFormat = this._gl.LUMINANCE;
  16886. break;
  16887. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16888. internalFormat = this._gl.LUMINANCE_ALPHA;
  16889. break;
  16890. case Engine.TEXTUREFORMAT_RGB:
  16891. internalFormat = this._gl.RGB;
  16892. break;
  16893. case Engine.TEXTUREFORMAT_RGBA:
  16894. internalFormat = this._gl.RGBA;
  16895. break;
  16896. case Engine.TEXTUREFORMAT_R:
  16897. internalFormat = this._gl.RED;
  16898. break;
  16899. case Engine.TEXTUREFORMAT_RG:
  16900. internalFormat = this._gl.RG;
  16901. break;
  16902. }
  16903. return internalFormat;
  16904. };
  16905. /** @hidden */
  16906. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16907. if (this._webGLVersion === 1) {
  16908. if (format !== undefined) {
  16909. switch (format) {
  16910. case Engine.TEXTUREFORMAT_LUMINANCE:
  16911. return this._gl.LUMINANCE;
  16912. case Engine.TEXTUREFORMAT_ALPHA:
  16913. return this._gl.ALPHA;
  16914. }
  16915. }
  16916. return this._gl.RGBA;
  16917. }
  16918. if (type === Engine.TEXTURETYPE_FLOAT) {
  16919. if (format !== undefined) {
  16920. switch (format) {
  16921. case Engine.TEXTUREFORMAT_R:
  16922. return this._gl.R32F;
  16923. case Engine.TEXTUREFORMAT_RG:
  16924. return this._gl.RG32F;
  16925. case Engine.TEXTUREFORMAT_RGB:
  16926. return this._gl.RGB32F;
  16927. }
  16928. }
  16929. return this._gl.RGBA32F;
  16930. }
  16931. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16932. if (format) {
  16933. switch (format) {
  16934. case Engine.TEXTUREFORMAT_R:
  16935. return this._gl.R16F;
  16936. case Engine.TEXTUREFORMAT_RG:
  16937. return this._gl.RG16F;
  16938. case Engine.TEXTUREFORMAT_RGB:
  16939. return this._gl.RGB16F;
  16940. }
  16941. }
  16942. return this._gl.RGBA16F;
  16943. }
  16944. if (format !== undefined) {
  16945. switch (format) {
  16946. case Engine.TEXTUREFORMAT_LUMINANCE:
  16947. return this._gl.LUMINANCE;
  16948. case Engine.TEXTUREFORMAT_RGB:
  16949. return this._gl.RGB;
  16950. case Engine.TEXTUREFORMAT_R:
  16951. return this._gl.R8;
  16952. case Engine.TEXTUREFORMAT_RG:
  16953. return this._gl.RG8;
  16954. case Engine.TEXTUREFORMAT_ALPHA:
  16955. return this._gl.ALPHA;
  16956. }
  16957. }
  16958. return this._gl.RGBA;
  16959. };
  16960. ;
  16961. /** @hidden */
  16962. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16963. if (type === Engine.TEXTURETYPE_FLOAT) {
  16964. return this._gl.RGBA32F;
  16965. }
  16966. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16967. return this._gl.RGBA16F;
  16968. }
  16969. return this._gl.RGBA8;
  16970. };
  16971. ;
  16972. /** @hidden */
  16973. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16974. var _this = this;
  16975. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16976. this._activeRequests.push(request);
  16977. request.onCompleteObservable.add(function (request) {
  16978. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16979. });
  16980. return request;
  16981. };
  16982. /** @hidden */
  16983. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16984. var _this = this;
  16985. return new Promise(function (resolve, reject) {
  16986. _this._loadFile(url, function (data) {
  16987. resolve(data);
  16988. }, undefined, database, useArrayBuffer, function (request, exception) {
  16989. reject(exception);
  16990. });
  16991. });
  16992. };
  16993. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16994. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16995. var onload = function (data) {
  16996. loadedFiles[index] = data;
  16997. loadedFiles._internalCount++;
  16998. if (loadedFiles._internalCount === 6) {
  16999. onfinish(loadedFiles);
  17000. }
  17001. };
  17002. var onerror = function (request, exception) {
  17003. if (onErrorCallBack && request) {
  17004. onErrorCallBack(request.status + " " + request.statusText, exception);
  17005. }
  17006. };
  17007. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17008. };
  17009. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17010. if (onError === void 0) { onError = null; }
  17011. var loadedFiles = [];
  17012. loadedFiles._internalCount = 0;
  17013. for (var index = 0; index < 6; index++) {
  17014. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17015. }
  17016. };
  17017. // Statics
  17018. /**
  17019. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17020. * @returns true if the engine can be created
  17021. * @ignorenaming
  17022. */
  17023. Engine.isSupported = function () {
  17024. try {
  17025. var tempcanvas = document.createElement("canvas");
  17026. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17027. return gl != null && !!window.WebGLRenderingContext;
  17028. }
  17029. catch (e) {
  17030. return false;
  17031. }
  17032. };
  17033. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17034. Engine.ExceptionList = [
  17035. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17036. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17037. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17038. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17039. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17040. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17041. ];
  17042. /** Gets the list of created engines */
  17043. Engine.Instances = new Array();
  17044. /**
  17045. * Hidden
  17046. */
  17047. Engine._TextureLoaders = [];
  17048. // Const statics
  17049. /** Defines that alpha blending is disabled */
  17050. Engine.ALPHA_DISABLE = 0;
  17051. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17052. Engine.ALPHA_ADD = 1;
  17053. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17054. Engine.ALPHA_COMBINE = 2;
  17055. /** Defines that alpha blending to DEST - SRC * DEST */
  17056. Engine.ALPHA_SUBTRACT = 3;
  17057. /** Defines that alpha blending to SRC * DEST */
  17058. Engine.ALPHA_MULTIPLY = 4;
  17059. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17060. Engine.ALPHA_MAXIMIZED = 5;
  17061. /** Defines that alpha blending to SRC + DEST */
  17062. Engine.ALPHA_ONEONE = 6;
  17063. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17064. Engine.ALPHA_PREMULTIPLIED = 7;
  17065. /**
  17066. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17067. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17068. */
  17069. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17070. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17071. Engine.ALPHA_INTERPOLATE = 9;
  17072. /**
  17073. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17074. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17075. */
  17076. Engine.ALPHA_SCREENMODE = 10;
  17077. /** Defines that the ressource is not delayed*/
  17078. Engine.DELAYLOADSTATE_NONE = 0;
  17079. /** Defines that the ressource was successfully delay loaded */
  17080. Engine.DELAYLOADSTATE_LOADED = 1;
  17081. /** Defines that the ressource is currently delay loading */
  17082. Engine.DELAYLOADSTATE_LOADING = 2;
  17083. /** Defines that the ressource is delayed and has not started loading */
  17084. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17085. // Depht or Stencil test Constants.
  17086. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17087. Engine.NEVER = 0x0200;
  17088. /** 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 */
  17089. Engine.ALWAYS = 0x0207;
  17090. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17091. Engine.LESS = 0x0201;
  17092. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17093. Engine.EQUAL = 0x0202;
  17094. /** 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 */
  17095. Engine.LEQUAL = 0x0203;
  17096. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17097. Engine.GREATER = 0x0204;
  17098. /** 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 */
  17099. Engine.GEQUAL = 0x0206;
  17100. /** 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 */
  17101. Engine.NOTEQUAL = 0x0205;
  17102. // Stencil Actions Constants.
  17103. /** Passed to stencilOperation to specify that stencil value must be kept */
  17104. Engine.KEEP = 0x1E00;
  17105. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17106. Engine.REPLACE = 0x1E01;
  17107. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17108. Engine.INCR = 0x1E02;
  17109. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17110. Engine.DECR = 0x1E03;
  17111. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17112. Engine.INVERT = 0x150A;
  17113. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17114. Engine.INCR_WRAP = 0x8507;
  17115. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17116. Engine.DECR_WRAP = 0x8508;
  17117. /** Texture is not repeating outside of 0..1 UVs */
  17118. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17119. /** Texture is repeating outside of 0..1 UVs */
  17120. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17121. /** Texture is repeating and mirrored */
  17122. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17123. /** ALPHA */
  17124. Engine.TEXTUREFORMAT_ALPHA = 0;
  17125. /** LUMINANCE */
  17126. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17127. /** LUMINANCE_ALPHA */
  17128. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17129. /** RGB */
  17130. Engine.TEXTUREFORMAT_RGB = 4;
  17131. /** RGBA */
  17132. Engine.TEXTUREFORMAT_RGBA = 5;
  17133. /** R */
  17134. Engine.TEXTUREFORMAT_R = 6;
  17135. /** RG */
  17136. Engine.TEXTUREFORMAT_RG = 7;
  17137. /** UNSIGNED_INT */
  17138. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17139. /** FLOAT */
  17140. Engine.TEXTURETYPE_FLOAT = 1;
  17141. /** HALF_FLOAT */
  17142. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17143. /** nearest is mag = nearest and min = nearest and mip = linear */
  17144. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17145. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17146. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17147. /** Trilinear is mag = linear and min = linear and mip = linear */
  17148. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17149. /** nearest is mag = nearest and min = nearest and mip = linear */
  17150. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17151. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17152. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17153. /** Trilinear is mag = linear and min = linear and mip = linear */
  17154. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17155. /** mag = nearest and min = nearest and mip = nearest */
  17156. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17157. /** mag = nearest and min = linear and mip = nearest */
  17158. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17159. /** mag = nearest and min = linear and mip = linear */
  17160. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17161. /** mag = nearest and min = linear and mip = none */
  17162. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17163. /** mag = nearest and min = nearest and mip = none */
  17164. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17165. /** mag = linear and min = nearest and mip = nearest */
  17166. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17167. /** mag = linear and min = nearest and mip = linear */
  17168. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17169. /** mag = linear and min = linear and mip = none */
  17170. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17171. /** mag = linear and min = nearest and mip = none */
  17172. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17173. /** Explicit coordinates mode */
  17174. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17175. /** Spherical coordinates mode */
  17176. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17177. /** Planar coordinates mode */
  17178. Engine.TEXTURE_PLANAR_MODE = 2;
  17179. /** Cubic coordinates mode */
  17180. Engine.TEXTURE_CUBIC_MODE = 3;
  17181. /** Projection coordinates mode */
  17182. Engine.TEXTURE_PROJECTION_MODE = 4;
  17183. /** Skybox coordinates mode */
  17184. Engine.TEXTURE_SKYBOX_MODE = 5;
  17185. /** Inverse Cubic coordinates mode */
  17186. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17187. /** Equirectangular coordinates mode */
  17188. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17189. /** Equirectangular Fixed coordinates mode */
  17190. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17191. /** Equirectangular Fixed Mirrored coordinates mode */
  17192. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17193. // Texture rescaling mode
  17194. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17195. Engine.SCALEMODE_FLOOR = 1;
  17196. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17197. Engine.SCALEMODE_NEAREST = 2;
  17198. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17199. Engine.SCALEMODE_CEILING = 3;
  17200. // Updatable statics so stick with vars here
  17201. /**
  17202. * Gets or sets the epsilon value used by collision engine
  17203. */
  17204. Engine.CollisionsEpsilon = 0.001;
  17205. /**
  17206. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17207. */
  17208. Engine.CodeRepository = "src/";
  17209. /**
  17210. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17211. */
  17212. Engine.ShadersRepository = "src/Shaders/";
  17213. return Engine;
  17214. }());
  17215. BABYLON.Engine = Engine;
  17216. })(BABYLON || (BABYLON = {}));
  17217. //# sourceMappingURL=babylon.engine.js.map
  17218. var BABYLON;
  17219. (function (BABYLON) {
  17220. /**
  17221. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17222. */
  17223. var Node = /** @class */ (function () {
  17224. /**
  17225. * Creates a new Node
  17226. * @param {string} name - the name and id to be given to this node
  17227. * @param {BABYLON.Scene} the scene this node will be added to
  17228. */
  17229. function Node(name, scene) {
  17230. if (scene === void 0) { scene = null; }
  17231. /**
  17232. * Gets or sets a string used to store user defined state for the node
  17233. */
  17234. this.state = "";
  17235. /**
  17236. * Gets or sets an object used to store user defined information for the node
  17237. */
  17238. this.metadata = null;
  17239. /**
  17240. * Gets or sets a boolean used to define if the node must be serialized
  17241. */
  17242. this.doNotSerialize = false;
  17243. /** @hidden */
  17244. this._isDisposed = false;
  17245. /**
  17246. * Gets a list of Animations associated with the node
  17247. */
  17248. this.animations = new Array();
  17249. this._ranges = {};
  17250. this._isEnabled = true;
  17251. this._isReady = true;
  17252. /** @hidden */
  17253. this._currentRenderId = -1;
  17254. this._parentRenderId = -1;
  17255. this._childRenderId = -1;
  17256. this._animationPropertiesOverride = null;
  17257. /**
  17258. * An event triggered when the mesh is disposed
  17259. */
  17260. this.onDisposeObservable = new BABYLON.Observable();
  17261. // Behaviors
  17262. this._behaviors = new Array();
  17263. this.name = name;
  17264. this.id = name;
  17265. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17266. this.uniqueId = this._scene.getUniqueId();
  17267. this._initCache();
  17268. }
  17269. /**
  17270. * Add a new node constructor
  17271. * @param type defines the type name of the node to construct
  17272. * @param constructorFunc defines the constructor function
  17273. */
  17274. Node.AddNodeConstructor = function (type, constructorFunc) {
  17275. this._NodeConstructors[type] = constructorFunc;
  17276. };
  17277. /**
  17278. * Returns a node constructor based on type name
  17279. * @param type defines the type name
  17280. * @param name defines the new node name
  17281. * @param scene defines the hosting scene
  17282. * @param options defines optional options to transmit to constructors
  17283. * @returns the new constructor or null
  17284. */
  17285. Node.Construct = function (type, name, scene, options) {
  17286. var constructorFunc = this._NodeConstructors[type];
  17287. if (!constructorFunc) {
  17288. return null;
  17289. }
  17290. return constructorFunc(name, scene, options);
  17291. };
  17292. /**
  17293. * Gets a boolean indicating if the node has been disposed
  17294. * @returns true if the node was disposed
  17295. */
  17296. Node.prototype.isDisposed = function () {
  17297. return this._isDisposed;
  17298. };
  17299. Object.defineProperty(Node.prototype, "parent", {
  17300. get: function () {
  17301. return this._parentNode;
  17302. },
  17303. /**
  17304. * Gets or sets the parent of the node
  17305. */
  17306. set: function (parent) {
  17307. if (this._parentNode === parent) {
  17308. return;
  17309. }
  17310. // Remove self from list of children of parent
  17311. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17312. var index = this._parentNode._children.indexOf(this);
  17313. if (index !== -1) {
  17314. this._parentNode._children.splice(index, 1);
  17315. }
  17316. }
  17317. // Store new parent
  17318. this._parentNode = parent;
  17319. // Add as child to new parent
  17320. if (this._parentNode) {
  17321. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17322. this._parentNode._children = new Array();
  17323. }
  17324. this._parentNode._children.push(this);
  17325. }
  17326. },
  17327. enumerable: true,
  17328. configurable: true
  17329. });
  17330. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17331. /**
  17332. * Gets or sets the animation properties override
  17333. */
  17334. get: function () {
  17335. if (!this._animationPropertiesOverride) {
  17336. return this._scene.animationPropertiesOverride;
  17337. }
  17338. return this._animationPropertiesOverride;
  17339. },
  17340. set: function (value) {
  17341. this._animationPropertiesOverride = value;
  17342. },
  17343. enumerable: true,
  17344. configurable: true
  17345. });
  17346. /**
  17347. * Gets a string idenfifying the name of the class
  17348. * @returns "Node" string
  17349. */
  17350. Node.prototype.getClassName = function () {
  17351. return "Node";
  17352. };
  17353. Object.defineProperty(Node.prototype, "onDispose", {
  17354. /**
  17355. * Sets a callback that will be raised when the node will be disposed
  17356. */
  17357. set: function (callback) {
  17358. if (this._onDisposeObserver) {
  17359. this.onDisposeObservable.remove(this._onDisposeObserver);
  17360. }
  17361. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17362. },
  17363. enumerable: true,
  17364. configurable: true
  17365. });
  17366. /**
  17367. * Gets the scene of the node
  17368. * @returns a {BABYLON.Scene}
  17369. */
  17370. Node.prototype.getScene = function () {
  17371. return this._scene;
  17372. };
  17373. /**
  17374. * Gets the engine of the node
  17375. * @returns a {BABYLON.Engine}
  17376. */
  17377. Node.prototype.getEngine = function () {
  17378. return this._scene.getEngine();
  17379. };
  17380. /**
  17381. * Attach a behavior to the node
  17382. * @see http://doc.babylonjs.com/features/behaviour
  17383. * @param behavior defines the behavior to attach
  17384. * @returns the current Node
  17385. */
  17386. Node.prototype.addBehavior = function (behavior) {
  17387. var _this = this;
  17388. var index = this._behaviors.indexOf(behavior);
  17389. if (index !== -1) {
  17390. return this;
  17391. }
  17392. behavior.init();
  17393. if (this._scene.isLoading) {
  17394. // We defer the attach when the scene will be loaded
  17395. this._scene.onDataLoadedObservable.addOnce(function () {
  17396. behavior.attach(_this);
  17397. });
  17398. }
  17399. else {
  17400. behavior.attach(this);
  17401. }
  17402. this._behaviors.push(behavior);
  17403. return this;
  17404. };
  17405. /**
  17406. * Remove an attached behavior
  17407. * @see http://doc.babylonjs.com/features/behaviour
  17408. * @param behavior defines the behavior to attach
  17409. * @returns the current Node
  17410. */
  17411. Node.prototype.removeBehavior = function (behavior) {
  17412. var index = this._behaviors.indexOf(behavior);
  17413. if (index === -1) {
  17414. return this;
  17415. }
  17416. this._behaviors[index].detach();
  17417. this._behaviors.splice(index, 1);
  17418. return this;
  17419. };
  17420. Object.defineProperty(Node.prototype, "behaviors", {
  17421. /**
  17422. * Gets the list of attached behaviors
  17423. * @see http://doc.babylonjs.com/features/behaviour
  17424. */
  17425. get: function () {
  17426. return this._behaviors;
  17427. },
  17428. enumerable: true,
  17429. configurable: true
  17430. });
  17431. /**
  17432. * Gets an attached behavior by name
  17433. * @param name defines the name of the behavior to look for
  17434. * @see http://doc.babylonjs.com/features/behaviour
  17435. * @returns null if behavior was not found else the requested behavior
  17436. */
  17437. Node.prototype.getBehaviorByName = function (name) {
  17438. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17439. var behavior = _a[_i];
  17440. if (behavior.name === name) {
  17441. return behavior;
  17442. }
  17443. }
  17444. return null;
  17445. };
  17446. /**
  17447. * Returns the world matrix of the node
  17448. * @returns a matrix containing the node's world matrix
  17449. */
  17450. Node.prototype.getWorldMatrix = function () {
  17451. return BABYLON.Matrix.Identity();
  17452. };
  17453. /** @hidden */
  17454. Node.prototype._getWorldMatrixDeterminant = function () {
  17455. return 1;
  17456. };
  17457. // override it in derived class if you add new variables to the cache
  17458. // and call the parent class method
  17459. /** @hidden */
  17460. Node.prototype._initCache = function () {
  17461. this._cache = {};
  17462. this._cache.parent = undefined;
  17463. };
  17464. /** @hidden */
  17465. Node.prototype.updateCache = function (force) {
  17466. if (!force && this.isSynchronized())
  17467. return;
  17468. this._cache.parent = this.parent;
  17469. this._updateCache();
  17470. };
  17471. // override it in derived class if you add new variables to the cache
  17472. // and call the parent class method if !ignoreParentClass
  17473. /** @hidden */
  17474. Node.prototype._updateCache = function (ignoreParentClass) {
  17475. };
  17476. // override it in derived class if you add new variables to the cache
  17477. /** @hidden */
  17478. Node.prototype._isSynchronized = function () {
  17479. return true;
  17480. };
  17481. /** @hidden */
  17482. Node.prototype._markSyncedWithParent = function () {
  17483. if (this.parent) {
  17484. this._parentRenderId = this.parent._childRenderId;
  17485. }
  17486. };
  17487. /** @hidden */
  17488. Node.prototype.isSynchronizedWithParent = function () {
  17489. if (!this.parent) {
  17490. return true;
  17491. }
  17492. if (this._parentRenderId !== this.parent._childRenderId) {
  17493. return false;
  17494. }
  17495. return this.parent.isSynchronized();
  17496. };
  17497. /** @hidden */
  17498. Node.prototype.isSynchronized = function (updateCache) {
  17499. var check = this.hasNewParent();
  17500. check = check || !this.isSynchronizedWithParent();
  17501. check = check || !this._isSynchronized();
  17502. if (updateCache)
  17503. this.updateCache(true);
  17504. return !check;
  17505. };
  17506. /** @hidden */
  17507. Node.prototype.hasNewParent = function (update) {
  17508. if (this._cache.parent === this.parent)
  17509. return false;
  17510. if (update)
  17511. this._cache.parent = this.parent;
  17512. return true;
  17513. };
  17514. /**
  17515. * Is this node ready to be used/rendered
  17516. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17517. * @return true if the node is ready
  17518. */
  17519. Node.prototype.isReady = function (completeCheck) {
  17520. if (completeCheck === void 0) { completeCheck = false; }
  17521. return this._isReady;
  17522. };
  17523. /**
  17524. * Is this node enabled?
  17525. * 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
  17526. * @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
  17527. * @return whether this node (and its parent) is enabled
  17528. */
  17529. Node.prototype.isEnabled = function (checkAncestors) {
  17530. if (checkAncestors === void 0) { checkAncestors = true; }
  17531. if (checkAncestors === false) {
  17532. return this._isEnabled;
  17533. }
  17534. if (this._isEnabled === false) {
  17535. return false;
  17536. }
  17537. if (this.parent !== undefined && this.parent !== null) {
  17538. return this.parent.isEnabled(checkAncestors);
  17539. }
  17540. return true;
  17541. };
  17542. /**
  17543. * Set the enabled state of this node
  17544. * @param value defines the new enabled state
  17545. */
  17546. Node.prototype.setEnabled = function (value) {
  17547. this._isEnabled = value;
  17548. };
  17549. /**
  17550. * Is this node a descendant of the given node?
  17551. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17552. * @param ancestor defines the parent node to inspect
  17553. * @returns a boolean indicating if this node is a descendant of the given node
  17554. */
  17555. Node.prototype.isDescendantOf = function (ancestor) {
  17556. if (this.parent) {
  17557. if (this.parent === ancestor) {
  17558. return true;
  17559. }
  17560. return this.parent.isDescendantOf(ancestor);
  17561. }
  17562. return false;
  17563. };
  17564. /** @hidden */
  17565. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17566. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17567. if (!this._children) {
  17568. return;
  17569. }
  17570. for (var index = 0; index < this._children.length; index++) {
  17571. var item = this._children[index];
  17572. if (!predicate || predicate(item)) {
  17573. results.push(item);
  17574. }
  17575. if (!directDescendantsOnly) {
  17576. item._getDescendants(results, false, predicate);
  17577. }
  17578. }
  17579. };
  17580. /**
  17581. * Will return all nodes that have this node as ascendant
  17582. * @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
  17583. * @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
  17584. * @return all children nodes of all types
  17585. */
  17586. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17587. var results = new Array();
  17588. this._getDescendants(results, directDescendantsOnly, predicate);
  17589. return results;
  17590. };
  17591. /**
  17592. * Get all child-meshes of this node
  17593. * @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
  17594. * @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
  17595. * @returns an array of {BABYLON.AbstractMesh}
  17596. */
  17597. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17598. var results = [];
  17599. this._getDescendants(results, directDescendantsOnly, function (node) {
  17600. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17601. });
  17602. return results;
  17603. };
  17604. /**
  17605. * Get all child-transformNodes of this node
  17606. * @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
  17607. * @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
  17608. * @returns an array of {BABYLON.TransformNode}
  17609. */
  17610. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17611. var results = [];
  17612. this._getDescendants(results, directDescendantsOnly, function (node) {
  17613. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17614. });
  17615. return results;
  17616. };
  17617. /**
  17618. * Get all direct children of this node
  17619. * @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
  17620. * @returns an array of {BABYLON.Node}
  17621. */
  17622. Node.prototype.getChildren = function (predicate) {
  17623. return this.getDescendants(true, predicate);
  17624. };
  17625. /** @hidden */
  17626. Node.prototype._setReady = function (state) {
  17627. if (state === this._isReady) {
  17628. return;
  17629. }
  17630. if (!state) {
  17631. this._isReady = false;
  17632. return;
  17633. }
  17634. if (this.onReady) {
  17635. this.onReady(this);
  17636. }
  17637. this._isReady = true;
  17638. };
  17639. /**
  17640. * Get an animation by name
  17641. * @param name defines the name of the animation to look for
  17642. * @returns null if not found else the requested animation
  17643. */
  17644. Node.prototype.getAnimationByName = function (name) {
  17645. for (var i = 0; i < this.animations.length; i++) {
  17646. var animation = this.animations[i];
  17647. if (animation.name === name) {
  17648. return animation;
  17649. }
  17650. }
  17651. return null;
  17652. };
  17653. /**
  17654. * Creates an animation range for this node
  17655. * @param name defines the name of the range
  17656. * @param from defines the starting key
  17657. * @param to defines the end key
  17658. */
  17659. Node.prototype.createAnimationRange = function (name, from, to) {
  17660. // check name not already in use
  17661. if (!this._ranges[name]) {
  17662. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17663. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17664. if (this.animations[i]) {
  17665. this.animations[i].createRange(name, from, to);
  17666. }
  17667. }
  17668. }
  17669. };
  17670. /**
  17671. * Delete a specific animation range
  17672. * @param name defines the name of the range to delete
  17673. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17674. */
  17675. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17676. if (deleteFrames === void 0) { deleteFrames = true; }
  17677. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17678. if (this.animations[i]) {
  17679. this.animations[i].deleteRange(name, deleteFrames);
  17680. }
  17681. }
  17682. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17683. };
  17684. /**
  17685. * Get an animation range by name
  17686. * @param name defines the name of the animation range to look for
  17687. * @returns null if not found else the requested animation range
  17688. */
  17689. Node.prototype.getAnimationRange = function (name) {
  17690. return this._ranges[name];
  17691. };
  17692. /**
  17693. * Will start the animation sequence
  17694. * @param name defines the range frames for animation sequence
  17695. * @param loop defines if the animation should loop (false by default)
  17696. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17697. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17698. * @returns the object created for this animation. If range does not exist, it will return null
  17699. */
  17700. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17701. var range = this.getAnimationRange(name);
  17702. if (!range) {
  17703. return null;
  17704. }
  17705. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17706. };
  17707. /**
  17708. * Serialize animation ranges into a JSON compatible object
  17709. * @returns serialization object
  17710. */
  17711. Node.prototype.serializeAnimationRanges = function () {
  17712. var serializationRanges = [];
  17713. for (var name in this._ranges) {
  17714. var localRange = this._ranges[name];
  17715. if (!localRange) {
  17716. continue;
  17717. }
  17718. var range = {};
  17719. range.name = name;
  17720. range.from = localRange.from;
  17721. range.to = localRange.to;
  17722. serializationRanges.push(range);
  17723. }
  17724. return serializationRanges;
  17725. };
  17726. /**
  17727. * Computes the world matrix of the node
  17728. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17729. * @returns the world matrix
  17730. */
  17731. Node.prototype.computeWorldMatrix = function (force) {
  17732. return BABYLON.Matrix.Identity();
  17733. };
  17734. /**
  17735. * Releases resources associated with this node.
  17736. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17737. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17738. */
  17739. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17740. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17741. if (!doNotRecurse) {
  17742. var nodes = this.getDescendants(true);
  17743. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17744. var node = nodes_1[_i];
  17745. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17746. }
  17747. }
  17748. else {
  17749. var transformNodes = this.getChildTransformNodes(true);
  17750. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17751. var transformNode = transformNodes_1[_a];
  17752. transformNode.parent = null;
  17753. transformNode.computeWorldMatrix(true);
  17754. }
  17755. }
  17756. this.parent = null;
  17757. // Callback
  17758. this.onDisposeObservable.notifyObservers(this);
  17759. this.onDisposeObservable.clear();
  17760. // Behaviors
  17761. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17762. var behavior = _c[_b];
  17763. behavior.detach();
  17764. }
  17765. this._behaviors = [];
  17766. this._isDisposed = true;
  17767. };
  17768. /**
  17769. * Parse animation range data from a serialization object and store them into a given node
  17770. * @param node defines where to store the animation ranges
  17771. * @param parsedNode defines the serialization object to read data from
  17772. * @param scene defines the hosting scene
  17773. */
  17774. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17775. if (parsedNode.ranges) {
  17776. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17777. var data = parsedNode.ranges[index];
  17778. node.createAnimationRange(data.name, data.from, data.to);
  17779. }
  17780. }
  17781. };
  17782. Node._NodeConstructors = {};
  17783. __decorate([
  17784. BABYLON.serialize()
  17785. ], Node.prototype, "name", void 0);
  17786. __decorate([
  17787. BABYLON.serialize()
  17788. ], Node.prototype, "id", void 0);
  17789. __decorate([
  17790. BABYLON.serialize()
  17791. ], Node.prototype, "uniqueId", void 0);
  17792. __decorate([
  17793. BABYLON.serialize()
  17794. ], Node.prototype, "state", void 0);
  17795. __decorate([
  17796. BABYLON.serialize()
  17797. ], Node.prototype, "metadata", void 0);
  17798. return Node;
  17799. }());
  17800. BABYLON.Node = Node;
  17801. })(BABYLON || (BABYLON = {}));
  17802. //# sourceMappingURL=babylon.node.js.map
  17803. var BABYLON;
  17804. (function (BABYLON) {
  17805. var BoundingSphere = /** @class */ (function () {
  17806. /**
  17807. * Creates a new bounding sphere
  17808. * @param min defines the minimum vector (in local space)
  17809. * @param max defines the maximum vector (in local space)
  17810. */
  17811. function BoundingSphere(min, max) {
  17812. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17813. this.reConstruct(min, max);
  17814. }
  17815. /**
  17816. * Recreates the entire bounding sphere from scratch
  17817. * @param min defines the new minimum vector (in local space)
  17818. * @param max defines the new maximum vector (in local space)
  17819. */
  17820. BoundingSphere.prototype.reConstruct = function (min, max) {
  17821. this.minimum = min.clone();
  17822. this.maximum = max.clone();
  17823. var distance = BABYLON.Vector3.Distance(min, max);
  17824. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17825. this.radius = distance * 0.5;
  17826. this.centerWorld = BABYLON.Vector3.Zero();
  17827. this._update(BABYLON.Matrix.Identity());
  17828. };
  17829. /**
  17830. * Scale the current bounding sphere by applying a scale factor
  17831. * @param factor defines the scale factor to apply
  17832. * @returns the current bounding box
  17833. */
  17834. BoundingSphere.prototype.scale = function (factor) {
  17835. var newRadius = this.radius * factor;
  17836. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17837. var min = this.center.subtract(newRadiusVector);
  17838. var max = this.center.add(newRadiusVector);
  17839. this.reConstruct(min, max);
  17840. return this;
  17841. };
  17842. // Methods
  17843. BoundingSphere.prototype._update = function (world) {
  17844. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17845. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17846. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17847. };
  17848. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17849. for (var i = 0; i < 6; i++) {
  17850. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17851. return false;
  17852. }
  17853. return true;
  17854. };
  17855. BoundingSphere.prototype.intersectsPoint = function (point) {
  17856. var x = this.centerWorld.x - point.x;
  17857. var y = this.centerWorld.y - point.y;
  17858. var z = this.centerWorld.z - point.z;
  17859. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17860. if (this.radiusWorld < distance)
  17861. return false;
  17862. return true;
  17863. };
  17864. // Statics
  17865. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17866. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17867. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17868. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17869. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17870. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17871. return false;
  17872. return true;
  17873. };
  17874. return BoundingSphere;
  17875. }());
  17876. BABYLON.BoundingSphere = BoundingSphere;
  17877. })(BABYLON || (BABYLON = {}));
  17878. //# sourceMappingURL=babylon.boundingSphere.js.map
  17879. var BABYLON;
  17880. (function (BABYLON) {
  17881. var BoundingBox = /** @class */ (function () {
  17882. /**
  17883. * Creates a new bounding box
  17884. * @param min defines the minimum vector (in local space)
  17885. * @param max defines the maximum vector (in local space)
  17886. */
  17887. function BoundingBox(min, max) {
  17888. this.vectorsWorld = new Array();
  17889. this.reConstruct(min, max);
  17890. }
  17891. // Methods
  17892. /**
  17893. * Recreates the entire bounding box from scratch
  17894. * @param min defines the new minimum vector (in local space)
  17895. * @param max defines the new maximum vector (in local space)
  17896. */
  17897. BoundingBox.prototype.reConstruct = function (min, max) {
  17898. this.minimum = min.clone();
  17899. this.maximum = max.clone();
  17900. // Bounding vectors
  17901. this.vectors = new Array();
  17902. this.vectors.push(this.minimum.clone());
  17903. this.vectors.push(this.maximum.clone());
  17904. this.vectors.push(this.minimum.clone());
  17905. this.vectors[2].x = this.maximum.x;
  17906. this.vectors.push(this.minimum.clone());
  17907. this.vectors[3].y = this.maximum.y;
  17908. this.vectors.push(this.minimum.clone());
  17909. this.vectors[4].z = this.maximum.z;
  17910. this.vectors.push(this.maximum.clone());
  17911. this.vectors[5].z = this.minimum.z;
  17912. this.vectors.push(this.maximum.clone());
  17913. this.vectors[6].x = this.minimum.x;
  17914. this.vectors.push(this.maximum.clone());
  17915. this.vectors[7].y = this.minimum.y;
  17916. // OBB
  17917. this.center = this.maximum.add(this.minimum).scale(0.5);
  17918. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17919. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17920. // World
  17921. for (var index = 0; index < this.vectors.length; index++) {
  17922. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17923. }
  17924. this.minimumWorld = BABYLON.Vector3.Zero();
  17925. this.maximumWorld = BABYLON.Vector3.Zero();
  17926. this.centerWorld = BABYLON.Vector3.Zero();
  17927. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17928. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17929. };
  17930. /**
  17931. * Scale the current bounding box by applying a scale factor
  17932. * @param factor defines the scale factor to apply
  17933. * @returns the current bounding box
  17934. */
  17935. BoundingBox.prototype.scale = function (factor) {
  17936. var diff = this.maximum.subtract(this.minimum);
  17937. var distance = diff.length() * factor;
  17938. diff.normalize();
  17939. var newRadius = diff.scale(distance / 2);
  17940. var min = this.center.subtract(newRadius);
  17941. var max = this.center.add(newRadius);
  17942. this.reConstruct(min, max);
  17943. return this;
  17944. };
  17945. BoundingBox.prototype.getWorldMatrix = function () {
  17946. return this._worldMatrix;
  17947. };
  17948. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17949. this._worldMatrix.copyFrom(matrix);
  17950. return this;
  17951. };
  17952. BoundingBox.prototype._update = function (world) {
  17953. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17954. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17955. for (var index = 0; index < this.vectors.length; index++) {
  17956. var v = this.vectorsWorld[index];
  17957. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17958. if (v.x < this.minimumWorld.x)
  17959. this.minimumWorld.x = v.x;
  17960. if (v.y < this.minimumWorld.y)
  17961. this.minimumWorld.y = v.y;
  17962. if (v.z < this.minimumWorld.z)
  17963. this.minimumWorld.z = v.z;
  17964. if (v.x > this.maximumWorld.x)
  17965. this.maximumWorld.x = v.x;
  17966. if (v.y > this.maximumWorld.y)
  17967. this.maximumWorld.y = v.y;
  17968. if (v.z > this.maximumWorld.z)
  17969. this.maximumWorld.z = v.z;
  17970. }
  17971. // Extend
  17972. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17973. this.extendSizeWorld.scaleInPlace(0.5);
  17974. // OBB
  17975. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17976. this.centerWorld.scaleInPlace(0.5);
  17977. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17978. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17979. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17980. this._worldMatrix = world;
  17981. };
  17982. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17983. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17984. };
  17985. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17986. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17987. };
  17988. BoundingBox.prototype.intersectsPoint = function (point) {
  17989. var delta = -BABYLON.Epsilon;
  17990. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17991. return false;
  17992. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17993. return false;
  17994. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17995. return false;
  17996. return true;
  17997. };
  17998. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17999. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18000. };
  18001. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18002. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18003. return false;
  18004. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18005. return false;
  18006. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18007. return false;
  18008. return true;
  18009. };
  18010. // Statics
  18011. BoundingBox.Intersects = function (box0, box1) {
  18012. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18013. return false;
  18014. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18015. return false;
  18016. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18017. return false;
  18018. return true;
  18019. };
  18020. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18021. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18022. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18023. return (num <= (sphereRadius * sphereRadius));
  18024. };
  18025. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18026. for (var p = 0; p < 6; p++) {
  18027. for (var i = 0; i < 8; i++) {
  18028. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18029. return false;
  18030. }
  18031. }
  18032. }
  18033. return true;
  18034. };
  18035. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18036. for (var p = 0; p < 6; p++) {
  18037. var inCount = 8;
  18038. for (var i = 0; i < 8; i++) {
  18039. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18040. --inCount;
  18041. }
  18042. else {
  18043. break;
  18044. }
  18045. }
  18046. if (inCount === 0)
  18047. return false;
  18048. }
  18049. return true;
  18050. };
  18051. return BoundingBox;
  18052. }());
  18053. BABYLON.BoundingBox = BoundingBox;
  18054. })(BABYLON || (BABYLON = {}));
  18055. //# sourceMappingURL=babylon.boundingBox.js.map
  18056. var BABYLON;
  18057. (function (BABYLON) {
  18058. var computeBoxExtents = function (axis, box) {
  18059. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18060. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18061. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18062. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18063. var r = r0 + r1 + r2;
  18064. return {
  18065. min: p - r,
  18066. max: p + r
  18067. };
  18068. };
  18069. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18070. var axisOverlap = function (axis, box0, box1) {
  18071. var result0 = computeBoxExtents(axis, box0);
  18072. var result1 = computeBoxExtents(axis, box1);
  18073. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18074. };
  18075. var BoundingInfo = /** @class */ (function () {
  18076. function BoundingInfo(minimum, maximum) {
  18077. this.minimum = minimum;
  18078. this.maximum = maximum;
  18079. this._isLocked = false;
  18080. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18081. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18082. }
  18083. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18084. get: function () {
  18085. return this._isLocked;
  18086. },
  18087. set: function (value) {
  18088. this._isLocked = value;
  18089. },
  18090. enumerable: true,
  18091. configurable: true
  18092. });
  18093. // Methods
  18094. BoundingInfo.prototype.update = function (world) {
  18095. if (this._isLocked) {
  18096. return;
  18097. }
  18098. this.boundingBox._update(world);
  18099. this.boundingSphere._update(world);
  18100. };
  18101. /**
  18102. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18103. * @param center New center of the bounding info
  18104. * @param extend New extend of the bounding info
  18105. */
  18106. BoundingInfo.prototype.centerOn = function (center, extend) {
  18107. this.minimum = center.subtract(extend);
  18108. this.maximum = center.add(extend);
  18109. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18110. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18111. return this;
  18112. };
  18113. /**
  18114. * Scale the current bounding info by applying a scale factor
  18115. * @param factor defines the scale factor to apply
  18116. * @returns the current bounding info
  18117. */
  18118. BoundingInfo.prototype.scale = function (factor) {
  18119. this.boundingBox.scale(factor);
  18120. this.boundingSphere.scale(factor);
  18121. return this;
  18122. };
  18123. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18124. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18125. return false;
  18126. return this.boundingBox.isInFrustum(frustumPlanes);
  18127. };
  18128. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18129. /**
  18130. * Gets the world distance between the min and max points of the bounding box
  18131. */
  18132. get: function () {
  18133. var boundingBox = this.boundingBox;
  18134. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18135. return size.length();
  18136. },
  18137. enumerable: true,
  18138. configurable: true
  18139. });
  18140. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18141. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18142. };
  18143. BoundingInfo.prototype._checkCollision = function (collider) {
  18144. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18145. };
  18146. BoundingInfo.prototype.intersectsPoint = function (point) {
  18147. if (!this.boundingSphere.centerWorld) {
  18148. return false;
  18149. }
  18150. if (!this.boundingSphere.intersectsPoint(point)) {
  18151. return false;
  18152. }
  18153. if (!this.boundingBox.intersectsPoint(point)) {
  18154. return false;
  18155. }
  18156. return true;
  18157. };
  18158. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18159. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18160. return false;
  18161. }
  18162. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18163. return false;
  18164. }
  18165. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18166. return false;
  18167. }
  18168. if (!precise) {
  18169. return true;
  18170. }
  18171. var box0 = this.boundingBox;
  18172. var box1 = boundingInfo.boundingBox;
  18173. if (!axisOverlap(box0.directions[0], box0, box1))
  18174. return false;
  18175. if (!axisOverlap(box0.directions[1], box0, box1))
  18176. return false;
  18177. if (!axisOverlap(box0.directions[2], box0, box1))
  18178. return false;
  18179. if (!axisOverlap(box1.directions[0], box0, box1))
  18180. return false;
  18181. if (!axisOverlap(box1.directions[1], box0, box1))
  18182. return false;
  18183. if (!axisOverlap(box1.directions[2], box0, box1))
  18184. return false;
  18185. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18186. return false;
  18187. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18188. return false;
  18189. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18190. return false;
  18191. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18192. return false;
  18193. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18194. return false;
  18195. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18196. return false;
  18197. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18198. return false;
  18199. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18200. return false;
  18201. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18202. return false;
  18203. return true;
  18204. };
  18205. return BoundingInfo;
  18206. }());
  18207. BABYLON.BoundingInfo = BoundingInfo;
  18208. })(BABYLON || (BABYLON = {}));
  18209. //# sourceMappingURL=babylon.boundingInfo.js.map
  18210. var BABYLON;
  18211. (function (BABYLON) {
  18212. var TransformNode = /** @class */ (function (_super) {
  18213. __extends(TransformNode, _super);
  18214. function TransformNode(name, scene, isPure) {
  18215. if (scene === void 0) { scene = null; }
  18216. if (isPure === void 0) { isPure = true; }
  18217. var _this = _super.call(this, name, scene) || this;
  18218. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18219. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18220. _this._up = new BABYLON.Vector3(0, 1, 0);
  18221. _this._right = new BABYLON.Vector3(1, 0, 0);
  18222. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18223. // Properties
  18224. _this._rotation = BABYLON.Vector3.Zero();
  18225. _this._scaling = BABYLON.Vector3.One();
  18226. _this._isDirty = false;
  18227. /**
  18228. * Set the billboard mode. Default is 0.
  18229. *
  18230. * | Value | Type | Description |
  18231. * | --- | --- | --- |
  18232. * | 0 | BILLBOARDMODE_NONE | |
  18233. * | 1 | BILLBOARDMODE_X | |
  18234. * | 2 | BILLBOARDMODE_Y | |
  18235. * | 4 | BILLBOARDMODE_Z | |
  18236. * | 7 | BILLBOARDMODE_ALL | |
  18237. *
  18238. */
  18239. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18240. _this.scalingDeterminant = 1;
  18241. _this.infiniteDistance = false;
  18242. /**
  18243. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18244. * By default the system will update normals to compensate
  18245. */
  18246. _this.ignoreNonUniformScaling = false;
  18247. _this.position = BABYLON.Vector3.Zero();
  18248. _this._localWorld = BABYLON.Matrix.Zero();
  18249. _this._worldMatrix = BABYLON.Matrix.Zero();
  18250. _this._worldMatrixDeterminant = 0;
  18251. _this._absolutePosition = BABYLON.Vector3.Zero();
  18252. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18253. _this._postMultiplyPivotMatrix = false;
  18254. _this._isWorldMatrixFrozen = false;
  18255. /**
  18256. * An event triggered after the world matrix is updated
  18257. */
  18258. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18259. _this._nonUniformScaling = false;
  18260. if (isPure) {
  18261. _this.getScene().addTransformNode(_this);
  18262. }
  18263. return _this;
  18264. }
  18265. /**
  18266. * Gets a string idenfifying the name of the class
  18267. * @returns "TransformNode" string
  18268. */
  18269. TransformNode.prototype.getClassName = function () {
  18270. return "TransformNode";
  18271. };
  18272. Object.defineProperty(TransformNode.prototype, "rotation", {
  18273. /**
  18274. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18275. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18276. * Default : (0.0, 0.0, 0.0)
  18277. */
  18278. get: function () {
  18279. return this._rotation;
  18280. },
  18281. set: function (newRotation) {
  18282. this._rotation = newRotation;
  18283. },
  18284. enumerable: true,
  18285. configurable: true
  18286. });
  18287. Object.defineProperty(TransformNode.prototype, "scaling", {
  18288. /**
  18289. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18290. * Default : (1.0, 1.0, 1.0)
  18291. */
  18292. get: function () {
  18293. return this._scaling;
  18294. },
  18295. /**
  18296. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18297. * Default : (1.0, 1.0, 1.0)
  18298. */
  18299. set: function (newScaling) {
  18300. this._scaling = newScaling;
  18301. },
  18302. enumerable: true,
  18303. configurable: true
  18304. });
  18305. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18306. /**
  18307. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18308. * It's null by default.
  18309. * 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)
  18310. */
  18311. get: function () {
  18312. return this._rotationQuaternion;
  18313. },
  18314. set: function (quaternion) {
  18315. this._rotationQuaternion = quaternion;
  18316. //reset the rotation vector.
  18317. if (quaternion && this.rotation.length()) {
  18318. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18319. }
  18320. },
  18321. enumerable: true,
  18322. configurable: true
  18323. });
  18324. Object.defineProperty(TransformNode.prototype, "forward", {
  18325. /**
  18326. * The forward direction of that transform in world space.
  18327. */
  18328. get: function () {
  18329. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18330. },
  18331. enumerable: true,
  18332. configurable: true
  18333. });
  18334. Object.defineProperty(TransformNode.prototype, "up", {
  18335. /**
  18336. * The up direction of that transform in world space.
  18337. */
  18338. get: function () {
  18339. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18340. },
  18341. enumerable: true,
  18342. configurable: true
  18343. });
  18344. Object.defineProperty(TransformNode.prototype, "right", {
  18345. /**
  18346. * The right direction of that transform in world space.
  18347. */
  18348. get: function () {
  18349. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18350. },
  18351. enumerable: true,
  18352. configurable: true
  18353. });
  18354. /**
  18355. * Returns the latest update of the World matrix
  18356. * Returns a Matrix.
  18357. */
  18358. TransformNode.prototype.getWorldMatrix = function () {
  18359. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18360. this.computeWorldMatrix();
  18361. }
  18362. return this._worldMatrix;
  18363. };
  18364. /** @hidden */
  18365. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18366. return this._worldMatrixDeterminant;
  18367. };
  18368. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18369. /**
  18370. * Returns directly the latest state of the mesh World matrix.
  18371. * A Matrix is returned.
  18372. */
  18373. get: function () {
  18374. return this._worldMatrix;
  18375. },
  18376. enumerable: true,
  18377. configurable: true
  18378. });
  18379. /**
  18380. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18381. * Returns the TransformNode.
  18382. */
  18383. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18384. this._poseMatrix.copyFrom(matrix);
  18385. return this;
  18386. };
  18387. /**
  18388. * Returns the mesh Pose matrix.
  18389. * Returned object : Matrix
  18390. */
  18391. TransformNode.prototype.getPoseMatrix = function () {
  18392. return this._poseMatrix;
  18393. };
  18394. TransformNode.prototype._isSynchronized = function () {
  18395. if (this._isDirty) {
  18396. return false;
  18397. }
  18398. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18399. return false;
  18400. if (this._cache.pivotMatrixUpdated) {
  18401. return false;
  18402. }
  18403. if (this.infiniteDistance) {
  18404. return false;
  18405. }
  18406. if (!this._cache.position.equals(this.position))
  18407. return false;
  18408. if (this.rotationQuaternion) {
  18409. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18410. return false;
  18411. }
  18412. if (!this._cache.rotation.equals(this.rotation))
  18413. return false;
  18414. if (!this._cache.scaling.equals(this.scaling))
  18415. return false;
  18416. return true;
  18417. };
  18418. TransformNode.prototype._initCache = function () {
  18419. _super.prototype._initCache.call(this);
  18420. this._cache.localMatrixUpdated = false;
  18421. this._cache.position = BABYLON.Vector3.Zero();
  18422. this._cache.scaling = BABYLON.Vector3.Zero();
  18423. this._cache.rotation = BABYLON.Vector3.Zero();
  18424. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18425. this._cache.billboardMode = -1;
  18426. };
  18427. TransformNode.prototype.markAsDirty = function (property) {
  18428. if (property === "rotation") {
  18429. this.rotationQuaternion = null;
  18430. }
  18431. this._currentRenderId = Number.MAX_VALUE;
  18432. this._isDirty = true;
  18433. return this;
  18434. };
  18435. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18436. /**
  18437. * Returns the current mesh absolute position.
  18438. * Retuns a Vector3.
  18439. */
  18440. get: function () {
  18441. return this._absolutePosition;
  18442. },
  18443. enumerable: true,
  18444. configurable: true
  18445. });
  18446. /**
  18447. * Sets a new matrix to apply before all other transformation
  18448. * @param matrix defines the transform matrix
  18449. * @returns the current TransformNode
  18450. */
  18451. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18452. return this.setPivotMatrix(matrix, false);
  18453. };
  18454. /**
  18455. * Sets a new pivot matrix to the current node
  18456. * @param matrix defines the new pivot matrix to use
  18457. * @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
  18458. * @returns the current TransformNode
  18459. */
  18460. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18461. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18462. this._pivotMatrix = matrix.clone();
  18463. this._cache.pivotMatrixUpdated = true;
  18464. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18465. if (this._postMultiplyPivotMatrix) {
  18466. if (!this._pivotMatrixInverse) {
  18467. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18468. }
  18469. else {
  18470. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18471. }
  18472. }
  18473. return this;
  18474. };
  18475. /**
  18476. * Returns the mesh pivot matrix.
  18477. * Default : Identity.
  18478. * A Matrix is returned.
  18479. */
  18480. TransformNode.prototype.getPivotMatrix = function () {
  18481. return this._pivotMatrix;
  18482. };
  18483. /**
  18484. * Prevents the World matrix to be computed any longer.
  18485. * Returns the TransformNode.
  18486. */
  18487. TransformNode.prototype.freezeWorldMatrix = function () {
  18488. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18489. this.computeWorldMatrix(true);
  18490. this._isWorldMatrixFrozen = true;
  18491. return this;
  18492. };
  18493. /**
  18494. * Allows back the World matrix computation.
  18495. * Returns the TransformNode.
  18496. */
  18497. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18498. this._isWorldMatrixFrozen = false;
  18499. this.computeWorldMatrix(true);
  18500. return this;
  18501. };
  18502. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18503. /**
  18504. * True if the World matrix has been frozen.
  18505. * Returns a boolean.
  18506. */
  18507. get: function () {
  18508. return this._isWorldMatrixFrozen;
  18509. },
  18510. enumerable: true,
  18511. configurable: true
  18512. });
  18513. /**
  18514. * Retuns the mesh absolute position in the World.
  18515. * Returns a Vector3.
  18516. */
  18517. TransformNode.prototype.getAbsolutePosition = function () {
  18518. this.computeWorldMatrix();
  18519. return this._absolutePosition;
  18520. };
  18521. /**
  18522. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18523. * Returns the TransformNode.
  18524. */
  18525. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18526. if (!absolutePosition) {
  18527. return this;
  18528. }
  18529. var absolutePositionX;
  18530. var absolutePositionY;
  18531. var absolutePositionZ;
  18532. if (absolutePosition.x === undefined) {
  18533. if (arguments.length < 3) {
  18534. return this;
  18535. }
  18536. absolutePositionX = arguments[0];
  18537. absolutePositionY = arguments[1];
  18538. absolutePositionZ = arguments[2];
  18539. }
  18540. else {
  18541. absolutePositionX = absolutePosition.x;
  18542. absolutePositionY = absolutePosition.y;
  18543. absolutePositionZ = absolutePosition.z;
  18544. }
  18545. if (this.parent) {
  18546. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18547. invertParentWorldMatrix.invert();
  18548. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18549. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18550. }
  18551. else {
  18552. this.position.x = absolutePositionX;
  18553. this.position.y = absolutePositionY;
  18554. this.position.z = absolutePositionZ;
  18555. }
  18556. return this;
  18557. };
  18558. /**
  18559. * Sets the mesh position in its local space.
  18560. * Returns the TransformNode.
  18561. */
  18562. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18563. this.computeWorldMatrix();
  18564. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18565. return this;
  18566. };
  18567. /**
  18568. * Returns the mesh position in the local space from the current World matrix values.
  18569. * Returns a new Vector3.
  18570. */
  18571. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18572. this.computeWorldMatrix();
  18573. var invLocalWorldMatrix = this._localWorld.clone();
  18574. invLocalWorldMatrix.invert();
  18575. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18576. };
  18577. /**
  18578. * Translates the mesh along the passed Vector3 in its local space.
  18579. * Returns the TransformNode.
  18580. */
  18581. TransformNode.prototype.locallyTranslate = function (vector3) {
  18582. this.computeWorldMatrix(true);
  18583. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18584. return this;
  18585. };
  18586. /**
  18587. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18588. * @param targetPoint the position (must be in same space as current mesh) to look at
  18589. * @param yawCor optional yaw (y-axis) correction in radians
  18590. * @param pitchCor optional pitch (x-axis) correction in radians
  18591. * @param rollCor optional roll (z-axis) correction in radians
  18592. * @param space the choosen space of the target
  18593. * @returns the TransformNode.
  18594. */
  18595. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18596. if (yawCor === void 0) { yawCor = 0; }
  18597. if (pitchCor === void 0) { pitchCor = 0; }
  18598. if (rollCor === void 0) { rollCor = 0; }
  18599. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18600. var dv = TransformNode._lookAtVectorCache;
  18601. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18602. targetPoint.subtractToRef(pos, dv);
  18603. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18604. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18605. var pitch = Math.atan2(dv.y, len);
  18606. if (this.rotationQuaternion) {
  18607. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18608. }
  18609. else {
  18610. this.rotation.x = pitch + pitchCor;
  18611. this.rotation.y = yaw + yawCor;
  18612. this.rotation.z = rollCor;
  18613. }
  18614. return this;
  18615. };
  18616. /**
  18617. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18618. * This Vector3 is expressed in the World space.
  18619. */
  18620. TransformNode.prototype.getDirection = function (localAxis) {
  18621. var result = BABYLON.Vector3.Zero();
  18622. this.getDirectionToRef(localAxis, result);
  18623. return result;
  18624. };
  18625. /**
  18626. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18627. * localAxis is expressed in the mesh local space.
  18628. * result is computed in the Wordl space from the mesh World matrix.
  18629. * Returns the TransformNode.
  18630. */
  18631. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18632. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18633. return this;
  18634. };
  18635. /**
  18636. * Sets a new pivot point to the current node
  18637. * @param point defines the new pivot point to use
  18638. * @param space defines if the point is in world or local space (local by default)
  18639. * @returns the current TransformNode
  18640. */
  18641. TransformNode.prototype.setPivotPoint = function (point, space) {
  18642. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18643. if (this.getScene().getRenderId() == 0) {
  18644. this.computeWorldMatrix(true);
  18645. }
  18646. var wm = this.getWorldMatrix();
  18647. if (space == BABYLON.Space.WORLD) {
  18648. var tmat = BABYLON.Tmp.Matrix[0];
  18649. wm.invertToRef(tmat);
  18650. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18651. }
  18652. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18653. };
  18654. /**
  18655. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18656. */
  18657. TransformNode.prototype.getPivotPoint = function () {
  18658. var point = BABYLON.Vector3.Zero();
  18659. this.getPivotPointToRef(point);
  18660. return point;
  18661. };
  18662. /**
  18663. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18664. * Returns the TransformNode.
  18665. */
  18666. TransformNode.prototype.getPivotPointToRef = function (result) {
  18667. result.x = -this._pivotMatrix.m[12];
  18668. result.y = -this._pivotMatrix.m[13];
  18669. result.z = -this._pivotMatrix.m[14];
  18670. return this;
  18671. };
  18672. /**
  18673. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18674. */
  18675. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18676. var point = BABYLON.Vector3.Zero();
  18677. this.getAbsolutePivotPointToRef(point);
  18678. return point;
  18679. };
  18680. /**
  18681. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18682. * Returns the TransformNode.
  18683. */
  18684. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18685. result.x = this._pivotMatrix.m[12];
  18686. result.y = this._pivotMatrix.m[13];
  18687. result.z = this._pivotMatrix.m[14];
  18688. this.getPivotPointToRef(result);
  18689. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18690. return this;
  18691. };
  18692. /**
  18693. * Defines the passed node as the parent of the current node.
  18694. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18695. * Returns the TransformNode.
  18696. */
  18697. TransformNode.prototype.setParent = function (node) {
  18698. if (!node && !this.parent) {
  18699. return this;
  18700. }
  18701. if (!node) {
  18702. var rotation = BABYLON.Tmp.Quaternion[0];
  18703. var position = BABYLON.Tmp.Vector3[0];
  18704. var scale = BABYLON.Tmp.Vector3[1];
  18705. if (this.parent && this.parent.computeWorldMatrix) {
  18706. this.parent.computeWorldMatrix(true);
  18707. }
  18708. this.computeWorldMatrix(true);
  18709. this.getWorldMatrix().decompose(scale, rotation, position);
  18710. if (this.rotationQuaternion) {
  18711. this.rotationQuaternion.copyFrom(rotation);
  18712. }
  18713. else {
  18714. rotation.toEulerAnglesToRef(this.rotation);
  18715. }
  18716. this.scaling.x = scale.x;
  18717. this.scaling.y = scale.y;
  18718. this.scaling.z = scale.z;
  18719. this.position.x = position.x;
  18720. this.position.y = position.y;
  18721. this.position.z = position.z;
  18722. }
  18723. else {
  18724. var rotation = BABYLON.Tmp.Quaternion[0];
  18725. var position = BABYLON.Tmp.Vector3[0];
  18726. var scale = BABYLON.Tmp.Vector3[1];
  18727. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18728. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18729. this.computeWorldMatrix(true);
  18730. node.computeWorldMatrix(true);
  18731. node.getWorldMatrix().invertToRef(invParentMatrix);
  18732. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18733. diffMatrix.decompose(scale, rotation, position);
  18734. if (this.rotationQuaternion) {
  18735. this.rotationQuaternion.copyFrom(rotation);
  18736. }
  18737. else {
  18738. rotation.toEulerAnglesToRef(this.rotation);
  18739. }
  18740. this.position.x = position.x;
  18741. this.position.y = position.y;
  18742. this.position.z = position.z;
  18743. this.scaling.x = scale.x;
  18744. this.scaling.y = scale.y;
  18745. this.scaling.z = scale.z;
  18746. }
  18747. this.parent = node;
  18748. return this;
  18749. };
  18750. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18751. get: function () {
  18752. return this._nonUniformScaling;
  18753. },
  18754. enumerable: true,
  18755. configurable: true
  18756. });
  18757. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18758. if (this._nonUniformScaling === value) {
  18759. return false;
  18760. }
  18761. this._nonUniformScaling = value;
  18762. return true;
  18763. };
  18764. /**
  18765. * Attach the current TransformNode to another TransformNode associated with a bone
  18766. * @param bone Bone affecting the TransformNode
  18767. * @param affectedTransformNode TransformNode associated with the bone
  18768. */
  18769. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18770. this._transformToBoneReferal = affectedTransformNode;
  18771. this.parent = bone;
  18772. if (bone.getWorldMatrix().determinant() < 0) {
  18773. this.scalingDeterminant *= -1;
  18774. }
  18775. return this;
  18776. };
  18777. TransformNode.prototype.detachFromBone = function () {
  18778. if (!this.parent) {
  18779. return this;
  18780. }
  18781. if (this.parent.getWorldMatrix().determinant() < 0) {
  18782. this.scalingDeterminant *= -1;
  18783. }
  18784. this._transformToBoneReferal = null;
  18785. this.parent = null;
  18786. return this;
  18787. };
  18788. /**
  18789. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18790. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18791. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18792. * The passed axis is also normalized.
  18793. * Returns the TransformNode.
  18794. */
  18795. TransformNode.prototype.rotate = function (axis, amount, space) {
  18796. axis.normalize();
  18797. if (!this.rotationQuaternion) {
  18798. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18799. this.rotation = BABYLON.Vector3.Zero();
  18800. }
  18801. var rotationQuaternion;
  18802. if (!space || space === BABYLON.Space.LOCAL) {
  18803. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18804. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18805. }
  18806. else {
  18807. if (this.parent) {
  18808. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18809. invertParentWorldMatrix.invert();
  18810. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18811. }
  18812. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18813. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18814. }
  18815. return this;
  18816. };
  18817. /**
  18818. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18819. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18820. * The passed axis is also normalized.
  18821. * Returns the TransformNode.
  18822. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18823. */
  18824. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18825. axis.normalize();
  18826. if (!this.rotationQuaternion) {
  18827. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18828. this.rotation.copyFromFloats(0, 0, 0);
  18829. }
  18830. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18831. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18832. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18833. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18834. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18835. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18836. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18837. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18838. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18839. return this;
  18840. };
  18841. /**
  18842. * Translates the mesh along the axis vector for the passed distance in the given space.
  18843. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18844. * Returns the TransformNode.
  18845. */
  18846. TransformNode.prototype.translate = function (axis, distance, space) {
  18847. var displacementVector = axis.scale(distance);
  18848. if (!space || space === BABYLON.Space.LOCAL) {
  18849. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18850. this.setPositionWithLocalVector(tempV3);
  18851. }
  18852. else {
  18853. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18854. }
  18855. return this;
  18856. };
  18857. /**
  18858. * Adds a rotation step to the mesh current rotation.
  18859. * x, y, z are Euler angles expressed in radians.
  18860. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18861. * This means this rotation is made in the mesh local space only.
  18862. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18863. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18864. * ```javascript
  18865. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18866. * ```
  18867. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18868. * 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.
  18869. * Returns the TransformNode.
  18870. */
  18871. TransformNode.prototype.addRotation = function (x, y, z) {
  18872. var rotationQuaternion;
  18873. if (this.rotationQuaternion) {
  18874. rotationQuaternion = this.rotationQuaternion;
  18875. }
  18876. else {
  18877. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18878. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18879. }
  18880. var accumulation = BABYLON.Tmp.Quaternion[0];
  18881. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18882. rotationQuaternion.multiplyInPlace(accumulation);
  18883. if (!this.rotationQuaternion) {
  18884. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18885. }
  18886. return this;
  18887. };
  18888. /**
  18889. * Computes the mesh World matrix and returns it.
  18890. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18891. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18892. * If the parameter `force`is set to `true`, the actual computation is done.
  18893. * Returns the mesh World Matrix.
  18894. */
  18895. TransformNode.prototype.computeWorldMatrix = function (force) {
  18896. if (this._isWorldMatrixFrozen) {
  18897. return this._worldMatrix;
  18898. }
  18899. if (!force && this.isSynchronized(true)) {
  18900. this._currentRenderId = this.getScene().getRenderId();
  18901. return this._worldMatrix;
  18902. }
  18903. this._cache.position.copyFrom(this.position);
  18904. this._cache.scaling.copyFrom(this.scaling);
  18905. this._cache.pivotMatrixUpdated = false;
  18906. this._cache.billboardMode = this.billboardMode;
  18907. this._currentRenderId = this.getScene().getRenderId();
  18908. this._childRenderId = this.getScene().getRenderId();
  18909. this._isDirty = false;
  18910. // Scaling
  18911. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18912. // Rotation
  18913. //rotate, if quaternion is set and rotation was used
  18914. if (this.rotationQuaternion) {
  18915. var len = this.rotation.length();
  18916. if (len) {
  18917. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18918. this.rotation.copyFromFloats(0, 0, 0);
  18919. }
  18920. }
  18921. if (this.rotationQuaternion) {
  18922. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18923. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18924. }
  18925. else {
  18926. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18927. this._cache.rotation.copyFrom(this.rotation);
  18928. }
  18929. // Translation
  18930. var camera = this.getScene().activeCamera;
  18931. if (this.infiniteDistance && !this.parent && camera) {
  18932. var cameraWorldMatrix = camera.getWorldMatrix();
  18933. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18934. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18935. }
  18936. else {
  18937. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18938. }
  18939. // Composing transformations
  18940. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18941. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18942. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18943. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18944. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18945. // Need to decompose each rotation here
  18946. var currentPosition = BABYLON.Tmp.Vector3[3];
  18947. if (this.parent && this.parent.getWorldMatrix) {
  18948. if (this._transformToBoneReferal) {
  18949. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18950. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18951. }
  18952. else {
  18953. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18954. }
  18955. }
  18956. else {
  18957. currentPosition.copyFrom(this.position);
  18958. }
  18959. currentPosition.subtractInPlace(camera.globalPosition);
  18960. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18961. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18962. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18963. }
  18964. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18965. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18966. }
  18967. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18968. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18969. }
  18970. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18971. }
  18972. else {
  18973. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18974. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18975. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18976. }
  18977. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18978. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18979. }
  18980. // Post multiply inverse of pivotMatrix
  18981. if (this._postMultiplyPivotMatrix) {
  18982. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  18983. }
  18984. // Local world
  18985. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18986. // Parent
  18987. if (this.parent && this.parent.getWorldMatrix) {
  18988. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18989. if (this._transformToBoneReferal) {
  18990. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18991. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18992. }
  18993. else {
  18994. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18995. }
  18996. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18997. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18998. this._worldMatrix.copyFrom(this._localWorld);
  18999. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19000. }
  19001. else {
  19002. if (this._transformToBoneReferal) {
  19003. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19004. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19005. }
  19006. else {
  19007. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19008. }
  19009. }
  19010. this._markSyncedWithParent();
  19011. }
  19012. else {
  19013. this._worldMatrix.copyFrom(this._localWorld);
  19014. }
  19015. // Normal matrix
  19016. if (!this.ignoreNonUniformScaling) {
  19017. if (this.scaling.isNonUniform) {
  19018. this._updateNonUniformScalingState(true);
  19019. }
  19020. else if (this.parent && this.parent._nonUniformScaling) {
  19021. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19022. }
  19023. else {
  19024. this._updateNonUniformScalingState(false);
  19025. }
  19026. }
  19027. else {
  19028. this._updateNonUniformScalingState(false);
  19029. }
  19030. this._afterComputeWorldMatrix();
  19031. // Absolute position
  19032. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19033. // Callbacks
  19034. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19035. if (!this._poseMatrix) {
  19036. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19037. }
  19038. // Cache the determinant
  19039. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19040. return this._worldMatrix;
  19041. };
  19042. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19043. };
  19044. /**
  19045. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19046. * @param func: callback function to add
  19047. *
  19048. * Returns the TransformNode.
  19049. */
  19050. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19051. this.onAfterWorldMatrixUpdateObservable.add(func);
  19052. return this;
  19053. };
  19054. /**
  19055. * Removes a registered callback function.
  19056. * Returns the TransformNode.
  19057. */
  19058. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19059. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19060. return this;
  19061. };
  19062. /**
  19063. * Clone the current transform node
  19064. * Returns the new transform node
  19065. * @param name Name of the new clone
  19066. * @param newParent New parent for the clone
  19067. * @param doNotCloneChildren Do not clone children hierarchy
  19068. */
  19069. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19070. var _this = this;
  19071. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19072. result.name = name;
  19073. result.id = name;
  19074. if (newParent) {
  19075. result.parent = newParent;
  19076. }
  19077. if (!doNotCloneChildren) {
  19078. // Children
  19079. var directDescendants = this.getDescendants(true);
  19080. for (var index = 0; index < directDescendants.length; index++) {
  19081. var child = directDescendants[index];
  19082. if (child.clone) {
  19083. child.clone(name + "." + child.name, result);
  19084. }
  19085. }
  19086. }
  19087. return result;
  19088. };
  19089. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19090. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19091. serializationObject.type = this.getClassName();
  19092. // Parent
  19093. if (this.parent) {
  19094. serializationObject.parentId = this.parent.id;
  19095. }
  19096. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19097. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19098. }
  19099. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19100. serializationObject.isEnabled = this.isEnabled();
  19101. // Parent
  19102. if (this.parent) {
  19103. serializationObject.parentId = this.parent.id;
  19104. }
  19105. return serializationObject;
  19106. };
  19107. // Statics
  19108. /**
  19109. * Returns a new TransformNode object parsed from the source provided.
  19110. * The parameter `parsedMesh` is the source.
  19111. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19112. */
  19113. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19114. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19115. if (BABYLON.Tags) {
  19116. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19117. }
  19118. if (parsedTransformNode.localMatrix) {
  19119. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19120. }
  19121. else if (parsedTransformNode.pivotMatrix) {
  19122. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19123. }
  19124. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19125. // Parent
  19126. if (parsedTransformNode.parentId) {
  19127. transformNode._waitingParentId = parsedTransformNode.parentId;
  19128. }
  19129. return transformNode;
  19130. };
  19131. /**
  19132. * Releases resources associated with this transform node.
  19133. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19134. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19135. */
  19136. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19137. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19138. // Animations
  19139. this.getScene().stopAnimation(this);
  19140. // Remove from scene
  19141. this.getScene().removeTransformNode(this);
  19142. this.onAfterWorldMatrixUpdateObservable.clear();
  19143. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19144. };
  19145. // Statics
  19146. TransformNode.BILLBOARDMODE_NONE = 0;
  19147. TransformNode.BILLBOARDMODE_X = 1;
  19148. TransformNode.BILLBOARDMODE_Y = 2;
  19149. TransformNode.BILLBOARDMODE_Z = 4;
  19150. TransformNode.BILLBOARDMODE_ALL = 7;
  19151. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19152. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19153. __decorate([
  19154. BABYLON.serializeAsVector3()
  19155. ], TransformNode.prototype, "_rotation", void 0);
  19156. __decorate([
  19157. BABYLON.serializeAsQuaternion()
  19158. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19159. __decorate([
  19160. BABYLON.serializeAsVector3()
  19161. ], TransformNode.prototype, "_scaling", void 0);
  19162. __decorate([
  19163. BABYLON.serialize()
  19164. ], TransformNode.prototype, "billboardMode", void 0);
  19165. __decorate([
  19166. BABYLON.serialize()
  19167. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19168. __decorate([
  19169. BABYLON.serialize()
  19170. ], TransformNode.prototype, "infiniteDistance", void 0);
  19171. __decorate([
  19172. BABYLON.serialize()
  19173. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19174. __decorate([
  19175. BABYLON.serializeAsVector3()
  19176. ], TransformNode.prototype, "position", void 0);
  19177. return TransformNode;
  19178. }(BABYLON.Node));
  19179. BABYLON.TransformNode = TransformNode;
  19180. })(BABYLON || (BABYLON = {}));
  19181. //# sourceMappingURL=babylon.transformNode.js.map
  19182. var BABYLON;
  19183. (function (BABYLON) {
  19184. /**
  19185. * Class used to store all common mesh properties
  19186. */
  19187. var AbstractMesh = /** @class */ (function (_super) {
  19188. __extends(AbstractMesh, _super);
  19189. // Constructor
  19190. /**
  19191. * Creates a new AbstractMesh
  19192. * @param name defines the name of the mesh
  19193. * @param scene defines the hosting scene
  19194. */
  19195. function AbstractMesh(name, scene) {
  19196. if (scene === void 0) { scene = null; }
  19197. var _this = _super.call(this, name, scene, false) || this;
  19198. _this._facetNb = 0; // facet number
  19199. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19200. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19201. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19202. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19203. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19204. _this._subDiv = {
  19205. max: 1,
  19206. X: 1,
  19207. Y: 1,
  19208. Z: 1
  19209. };
  19210. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19211. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19212. // Events
  19213. /**
  19214. * An event triggered when this mesh collides with another one
  19215. */
  19216. _this.onCollideObservable = new BABYLON.Observable();
  19217. /**
  19218. * An event triggered when the collision's position changes
  19219. */
  19220. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19221. /**
  19222. * An event triggered when material is changed
  19223. */
  19224. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19225. // Properties
  19226. /**
  19227. * Gets or sets the orientation for POV movement & rotation
  19228. */
  19229. _this.definedFacingForward = true;
  19230. /**
  19231. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19232. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19233. * * 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.
  19234. * @see http://doc.babylonjs.com/features/occlusionquery
  19235. */
  19236. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19237. /**
  19238. * 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:
  19239. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19240. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19241. * * 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.
  19242. * @see http://doc.babylonjs.com/features/occlusionquery
  19243. */
  19244. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19245. /**
  19246. * 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.
  19247. * The default value is -1 which means don't break the query and wait till the result
  19248. * @see http://doc.babylonjs.com/features/occlusionquery
  19249. */
  19250. _this.occlusionRetryCount = -1;
  19251. /** @hidden */
  19252. _this._occlusionInternalRetryCounter = 0;
  19253. /** @hidden */
  19254. _this._isOccluded = false;
  19255. /** @hidden */
  19256. _this._isOcclusionQueryInProgress = false;
  19257. _this._visibility = 1.0;
  19258. /** Gets or sets the alpha index used to sort transparent meshes
  19259. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19260. */
  19261. _this.alphaIndex = Number.MAX_VALUE;
  19262. /**
  19263. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19264. */
  19265. _this.isVisible = true;
  19266. /**
  19267. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19268. */
  19269. _this.isPickable = true;
  19270. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19271. _this.showSubMeshesBoundingBox = false;
  19272. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19273. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19274. */
  19275. _this.isBlocker = false;
  19276. /**
  19277. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19278. */
  19279. _this.enablePointerMoveEvents = false;
  19280. /**
  19281. * Specifies the rendering group id for this mesh (0 by default)
  19282. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19283. */
  19284. _this.renderingGroupId = 0;
  19285. _this._receiveShadows = false;
  19286. /**
  19287. * Gets or sets a boolean indicating if the outline must be rendered as well
  19288. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19289. */
  19290. _this.renderOutline = false;
  19291. /** Defines color to use when rendering outline */
  19292. _this.outlineColor = BABYLON.Color3.Red();
  19293. /** Define width to use when rendering outline */
  19294. _this.outlineWidth = 0.02;
  19295. /**
  19296. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19297. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19298. */
  19299. _this.renderOverlay = false;
  19300. /** Defines color to use when rendering overlay */
  19301. _this.overlayColor = BABYLON.Color3.Red();
  19302. /** Defines alpha to use when rendering overlay */
  19303. _this.overlayAlpha = 0.5;
  19304. _this._hasVertexAlpha = false;
  19305. _this._useVertexColors = true;
  19306. _this._computeBonesUsingShaders = true;
  19307. _this._numBoneInfluencers = 4;
  19308. _this._applyFog = true;
  19309. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19310. _this.useOctreeForRenderingSelection = true;
  19311. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19312. _this.useOctreeForPicking = true;
  19313. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19314. _this.useOctreeForCollisions = true;
  19315. _this._layerMask = 0x0FFFFFFF;
  19316. /**
  19317. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19318. */
  19319. _this.alwaysSelectAsActiveMesh = false;
  19320. /**
  19321. * Gets or sets the current action manager
  19322. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19323. */
  19324. _this.actionManager = null;
  19325. /**
  19326. * Gets or sets impostor used for physic simulation
  19327. * @see http://doc.babylonjs.com/features/physics_engine
  19328. */
  19329. _this.physicsImpostor = null;
  19330. // Collisions
  19331. _this._checkCollisions = false;
  19332. _this._collisionMask = -1;
  19333. _this._collisionGroup = -1;
  19334. /**
  19335. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19336. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19337. */
  19338. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19339. /**
  19340. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19341. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19342. */
  19343. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19344. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19345. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19346. // Edges
  19347. /**
  19348. * Defines edge width used when edgesRenderer is enabled
  19349. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19350. */
  19351. _this.edgesWidth = 1;
  19352. /**
  19353. * Defines edge color used when edgesRenderer is enabled
  19354. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19355. */
  19356. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19357. // Cache
  19358. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19359. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19360. /** @hidden */
  19361. _this._renderId = 0;
  19362. /** @hidden */
  19363. _this._intersectionsInProgress = new Array();
  19364. /** @hidden */
  19365. _this._unIndexed = false;
  19366. /** @hidden */
  19367. _this._lightSources = new Array();
  19368. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19369. if (collidedMesh === void 0) { collidedMesh = null; }
  19370. //TODO move this to the collision coordinator!
  19371. if (_this.getScene().workerCollisions)
  19372. newPosition.multiplyInPlace(_this._collider._radius);
  19373. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19374. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19375. _this.position.addInPlace(_this._diffPositionForCollisions);
  19376. }
  19377. if (collidedMesh) {
  19378. _this.onCollideObservable.notifyObservers(collidedMesh);
  19379. }
  19380. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19381. };
  19382. _this.getScene().addMesh(_this);
  19383. _this._resyncLightSources();
  19384. return _this;
  19385. }
  19386. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19387. /**
  19388. * No billboard
  19389. */
  19390. get: function () {
  19391. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19397. /** Billboard on X axis */
  19398. get: function () {
  19399. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19400. },
  19401. enumerable: true,
  19402. configurable: true
  19403. });
  19404. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19405. /** Billboard on Y axis */
  19406. get: function () {
  19407. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19413. /** Billboard on Z axis */
  19414. get: function () {
  19415. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19416. },
  19417. enumerable: true,
  19418. configurable: true
  19419. });
  19420. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19421. /** Billboard on all axes */
  19422. get: function () {
  19423. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19429. /**
  19430. * Gets the number of facets in the mesh
  19431. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19432. */
  19433. get: function () {
  19434. return this._facetNb;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19440. /**
  19441. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19442. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19443. */
  19444. get: function () {
  19445. return this._partitioningSubdivisions;
  19446. },
  19447. set: function (nb) {
  19448. this._partitioningSubdivisions = nb;
  19449. },
  19450. enumerable: true,
  19451. configurable: true
  19452. });
  19453. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19454. /**
  19455. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19456. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19457. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19458. */
  19459. get: function () {
  19460. return this._partitioningBBoxRatio;
  19461. },
  19462. set: function (ratio) {
  19463. this._partitioningBBoxRatio = ratio;
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19469. /**
  19470. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19471. * Works only for updatable meshes.
  19472. * Doesn't work with multi-materials
  19473. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19474. */
  19475. get: function () {
  19476. return this._facetDepthSort;
  19477. },
  19478. set: function (sort) {
  19479. this._facetDepthSort = sort;
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19485. /**
  19486. * The location (Vector3) where the facet depth sort must be computed from.
  19487. * By default, the active camera position.
  19488. * Used only when facet depth sort is enabled
  19489. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19490. */
  19491. get: function () {
  19492. return this._facetDepthSortFrom;
  19493. },
  19494. set: function (location) {
  19495. this._facetDepthSortFrom = location;
  19496. },
  19497. enumerable: true,
  19498. configurable: true
  19499. });
  19500. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19501. /**
  19502. * gets a boolean indicating if facetData is enabled
  19503. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19504. */
  19505. get: function () {
  19506. return this._facetDataEnabled;
  19507. },
  19508. enumerable: true,
  19509. configurable: true
  19510. });
  19511. /** @hidden */
  19512. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19513. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19514. return false;
  19515. }
  19516. this._markSubMeshesAsMiscDirty();
  19517. return true;
  19518. };
  19519. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19520. /** Set a function to call when this mesh collides with another one */
  19521. set: function (callback) {
  19522. if (this._onCollideObserver) {
  19523. this.onCollideObservable.remove(this._onCollideObserver);
  19524. }
  19525. this._onCollideObserver = this.onCollideObservable.add(callback);
  19526. },
  19527. enumerable: true,
  19528. configurable: true
  19529. });
  19530. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19531. /** Set a function to call when the collision's position changes */
  19532. set: function (callback) {
  19533. if (this._onCollisionPositionChangeObserver) {
  19534. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19535. }
  19536. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19537. },
  19538. enumerable: true,
  19539. configurable: true
  19540. });
  19541. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19542. /**
  19543. * 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
  19544. * @see http://doc.babylonjs.com/features/occlusionquery
  19545. */
  19546. get: function () {
  19547. return this._isOccluded;
  19548. },
  19549. set: function (value) {
  19550. this._isOccluded = value;
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19556. /**
  19557. * Flag to check the progress status of the query
  19558. * @see http://doc.babylonjs.com/features/occlusionquery
  19559. */
  19560. get: function () {
  19561. return this._isOcclusionQueryInProgress;
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19567. /**
  19568. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19569. */
  19570. get: function () {
  19571. return this._visibility;
  19572. },
  19573. /**
  19574. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19575. */
  19576. set: function (value) {
  19577. if (this._visibility === value) {
  19578. return;
  19579. }
  19580. this._visibility = value;
  19581. this._markSubMeshesAsMiscDirty();
  19582. },
  19583. enumerable: true,
  19584. configurable: true
  19585. });
  19586. Object.defineProperty(AbstractMesh.prototype, "material", {
  19587. /** Gets or sets current material */
  19588. get: function () {
  19589. return this._material;
  19590. },
  19591. set: function (value) {
  19592. if (this._material === value) {
  19593. return;
  19594. }
  19595. this._material = value;
  19596. if (this.onMaterialChangedObservable.hasObservers) {
  19597. this.onMaterialChangedObservable.notifyObservers(this);
  19598. }
  19599. if (!this.subMeshes) {
  19600. return;
  19601. }
  19602. this._unBindEffect();
  19603. },
  19604. enumerable: true,
  19605. configurable: true
  19606. });
  19607. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19608. /**
  19609. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19610. * @see http://doc.babylonjs.com/babylon101/shadows
  19611. */
  19612. get: function () {
  19613. return this._receiveShadows;
  19614. },
  19615. set: function (value) {
  19616. if (this._receiveShadows === value) {
  19617. return;
  19618. }
  19619. this._receiveShadows = value;
  19620. this._markSubMeshesAsLightDirty();
  19621. },
  19622. enumerable: true,
  19623. configurable: true
  19624. });
  19625. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19626. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19627. get: function () {
  19628. return this._hasVertexAlpha;
  19629. },
  19630. set: function (value) {
  19631. if (this._hasVertexAlpha === value) {
  19632. return;
  19633. }
  19634. this._hasVertexAlpha = value;
  19635. this._markSubMeshesAsAttributesDirty();
  19636. this._markSubMeshesAsMiscDirty();
  19637. },
  19638. enumerable: true,
  19639. configurable: true
  19640. });
  19641. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19642. /** 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) */
  19643. get: function () {
  19644. return this._useVertexColors;
  19645. },
  19646. set: function (value) {
  19647. if (this._useVertexColors === value) {
  19648. return;
  19649. }
  19650. this._useVertexColors = value;
  19651. this._markSubMeshesAsAttributesDirty();
  19652. },
  19653. enumerable: true,
  19654. configurable: true
  19655. });
  19656. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19657. /**
  19658. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19659. */
  19660. get: function () {
  19661. return this._computeBonesUsingShaders;
  19662. },
  19663. set: function (value) {
  19664. if (this._computeBonesUsingShaders === value) {
  19665. return;
  19666. }
  19667. this._computeBonesUsingShaders = value;
  19668. this._markSubMeshesAsAttributesDirty();
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19674. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19675. get: function () {
  19676. return this._numBoneInfluencers;
  19677. },
  19678. set: function (value) {
  19679. if (this._numBoneInfluencers === value) {
  19680. return;
  19681. }
  19682. this._numBoneInfluencers = value;
  19683. this._markSubMeshesAsAttributesDirty();
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19689. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19690. get: function () {
  19691. return this._applyFog;
  19692. },
  19693. set: function (value) {
  19694. if (this._applyFog === value) {
  19695. return;
  19696. }
  19697. this._applyFog = value;
  19698. this._markSubMeshesAsMiscDirty();
  19699. },
  19700. enumerable: true,
  19701. configurable: true
  19702. });
  19703. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19704. /**
  19705. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19706. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19707. */
  19708. get: function () {
  19709. return this._layerMask;
  19710. },
  19711. set: function (value) {
  19712. if (value === this._layerMask) {
  19713. return;
  19714. }
  19715. this._layerMask = value;
  19716. this._resyncLightSources();
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19722. /**
  19723. * Gets or sets a collision mask used to mask collisions (default is -1).
  19724. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19725. */
  19726. get: function () {
  19727. return this._collisionMask;
  19728. },
  19729. set: function (mask) {
  19730. this._collisionMask = !isNaN(mask) ? mask : -1;
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19736. /**
  19737. * Gets or sets the current collision group mask (-1 by default).
  19738. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19739. */
  19740. get: function () {
  19741. return this._collisionGroup;
  19742. },
  19743. set: function (mask) {
  19744. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19750. /** @hidden */
  19751. get: function () {
  19752. return null;
  19753. },
  19754. enumerable: true,
  19755. configurable: true
  19756. });
  19757. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19758. get: function () {
  19759. return this._skeleton;
  19760. },
  19761. /**
  19762. * Gets or sets a skeleton to apply skining transformations
  19763. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19764. */
  19765. set: function (value) {
  19766. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19767. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19768. }
  19769. if (value && value.needInitialSkinMatrix) {
  19770. value._registerMeshWithPoseMatrix(this);
  19771. }
  19772. this._skeleton = value;
  19773. if (!this._skeleton) {
  19774. this._bonesTransformMatrices = null;
  19775. }
  19776. this._markSubMeshesAsAttributesDirty();
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. /**
  19782. * Returns the string "AbstractMesh"
  19783. * @returns "AbstractMesh"
  19784. */
  19785. AbstractMesh.prototype.getClassName = function () {
  19786. return "AbstractMesh";
  19787. };
  19788. /**
  19789. * Gets a string representation of the current mesh
  19790. * @param fullDetails defines a boolean indicating if full details must be included
  19791. * @returns a string representation of the current mesh
  19792. */
  19793. AbstractMesh.prototype.toString = function (fullDetails) {
  19794. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19795. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19796. if (this._skeleton) {
  19797. ret += ", skeleton: " + this._skeleton.name;
  19798. }
  19799. if (fullDetails) {
  19800. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19801. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19802. }
  19803. return ret;
  19804. };
  19805. /** @hidden */
  19806. AbstractMesh.prototype._rebuild = function () {
  19807. if (this._occlusionQuery) {
  19808. this._occlusionQuery = null;
  19809. }
  19810. if (this._edgesRenderer) {
  19811. this._edgesRenderer._rebuild();
  19812. }
  19813. if (!this.subMeshes) {
  19814. return;
  19815. }
  19816. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19817. var subMesh = _a[_i];
  19818. subMesh._rebuild();
  19819. }
  19820. };
  19821. /** @hidden */
  19822. AbstractMesh.prototype._resyncLightSources = function () {
  19823. this._lightSources.length = 0;
  19824. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19825. var light = _a[_i];
  19826. if (!light.isEnabled()) {
  19827. continue;
  19828. }
  19829. if (light.canAffectMesh(this)) {
  19830. this._lightSources.push(light);
  19831. }
  19832. }
  19833. this._markSubMeshesAsLightDirty();
  19834. };
  19835. /** @hidden */
  19836. AbstractMesh.prototype._resyncLighSource = function (light) {
  19837. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19838. var index = this._lightSources.indexOf(light);
  19839. if (index === -1) {
  19840. if (!isIn) {
  19841. return;
  19842. }
  19843. this._lightSources.push(light);
  19844. }
  19845. else {
  19846. if (isIn) {
  19847. return;
  19848. }
  19849. this._lightSources.splice(index, 1);
  19850. }
  19851. this._markSubMeshesAsLightDirty();
  19852. };
  19853. /** @hidden */
  19854. AbstractMesh.prototype._unBindEffect = function () {
  19855. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19856. var subMesh = _a[_i];
  19857. subMesh.setEffect(null);
  19858. }
  19859. };
  19860. /** @hidden */
  19861. AbstractMesh.prototype._removeLightSource = function (light) {
  19862. var index = this._lightSources.indexOf(light);
  19863. if (index === -1) {
  19864. return;
  19865. }
  19866. this._lightSources.splice(index, 1);
  19867. this._markSubMeshesAsLightDirty();
  19868. };
  19869. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19870. if (!this.subMeshes) {
  19871. return;
  19872. }
  19873. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19874. var subMesh = _a[_i];
  19875. if (subMesh._materialDefines) {
  19876. func(subMesh._materialDefines);
  19877. }
  19878. }
  19879. };
  19880. /** @hidden */
  19881. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19882. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19883. };
  19884. /** @hidden */
  19885. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19886. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19887. };
  19888. /** @hidden */
  19889. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19890. if (!this.subMeshes) {
  19891. return;
  19892. }
  19893. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19894. var subMesh = _a[_i];
  19895. var material = subMesh.getMaterial();
  19896. if (material) {
  19897. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19898. }
  19899. }
  19900. };
  19901. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19902. /**
  19903. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19904. */
  19905. get: function () {
  19906. return this._scaling;
  19907. },
  19908. set: function (newScaling) {
  19909. this._scaling = newScaling;
  19910. if (this.physicsImpostor) {
  19911. this.physicsImpostor.forceUpdate();
  19912. }
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. // Methods
  19918. /**
  19919. * Disables the mesh edge rendering mode
  19920. * @returns the currentAbstractMesh
  19921. */
  19922. AbstractMesh.prototype.disableEdgesRendering = function () {
  19923. if (this._edgesRenderer) {
  19924. this._edgesRenderer.dispose();
  19925. this._edgesRenderer = null;
  19926. }
  19927. return this;
  19928. };
  19929. /**
  19930. * Enables the edge rendering mode on the mesh.
  19931. * This mode makes the mesh edges visible
  19932. * @param epsilon defines the maximal distance between two angles to detect a face
  19933. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19934. * @returns the currentAbstractMesh
  19935. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19936. */
  19937. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19938. if (epsilon === void 0) { epsilon = 0.95; }
  19939. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19940. this.disableEdgesRendering();
  19941. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19942. return this;
  19943. };
  19944. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  19945. /**
  19946. * Gets the edgesRenderer associated with the mesh
  19947. */
  19948. get: function () {
  19949. return this._edgesRenderer;
  19950. },
  19951. enumerable: true,
  19952. configurable: true
  19953. });
  19954. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19955. /**
  19956. * Returns true if the mesh is blocked. Implemented by child classes
  19957. */
  19958. get: function () {
  19959. return false;
  19960. },
  19961. enumerable: true,
  19962. configurable: true
  19963. });
  19964. /**
  19965. * Returns the mesh itself by default. Implemented by child classes
  19966. * @param camera defines the camera to use to pick the right LOD level
  19967. * @returns the currentAbstractMesh
  19968. */
  19969. AbstractMesh.prototype.getLOD = function (camera) {
  19970. return this;
  19971. };
  19972. /**
  19973. * Returns 0 by default. Implemented by child classes
  19974. * @returns an integer
  19975. */
  19976. AbstractMesh.prototype.getTotalVertices = function () {
  19977. return 0;
  19978. };
  19979. /**
  19980. * Returns null by default. Implemented by child classes
  19981. * @returns null
  19982. */
  19983. AbstractMesh.prototype.getIndices = function () {
  19984. return null;
  19985. };
  19986. /**
  19987. * Returns the array of the requested vertex data kind. Implemented by child classes
  19988. * @param kind defines the vertex data kind to use
  19989. * @returns null
  19990. */
  19991. AbstractMesh.prototype.getVerticesData = function (kind) {
  19992. return null;
  19993. };
  19994. /**
  19995. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19996. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19997. * Note that a new underlying VertexBuffer object is created each call.
  19998. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19999. * @param kind defines vertex data kind:
  20000. * * BABYLON.VertexBuffer.PositionKind
  20001. * * BABYLON.VertexBuffer.UVKind
  20002. * * BABYLON.VertexBuffer.UV2Kind
  20003. * * BABYLON.VertexBuffer.UV3Kind
  20004. * * BABYLON.VertexBuffer.UV4Kind
  20005. * * BABYLON.VertexBuffer.UV5Kind
  20006. * * BABYLON.VertexBuffer.UV6Kind
  20007. * * BABYLON.VertexBuffer.ColorKind
  20008. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20009. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20010. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20011. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20012. * @param data defines the data source
  20013. * @param updatable defines if the data must be flagged as updatable (or static)
  20014. * @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
  20015. * @returns the current mesh
  20016. */
  20017. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20018. return this;
  20019. };
  20020. /**
  20021. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20022. * If the mesh has no geometry, it is simply returned as it is.
  20023. * @param kind defines vertex data kind:
  20024. * * BABYLON.VertexBuffer.PositionKind
  20025. * * BABYLON.VertexBuffer.UVKind
  20026. * * BABYLON.VertexBuffer.UV2Kind
  20027. * * BABYLON.VertexBuffer.UV3Kind
  20028. * * BABYLON.VertexBuffer.UV4Kind
  20029. * * BABYLON.VertexBuffer.UV5Kind
  20030. * * BABYLON.VertexBuffer.UV6Kind
  20031. * * BABYLON.VertexBuffer.ColorKind
  20032. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20033. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20034. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20035. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20036. * @param data defines the data source
  20037. * @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
  20038. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20039. * @returns the current mesh
  20040. */
  20041. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20042. return this;
  20043. };
  20044. /**
  20045. * Sets the mesh indices,
  20046. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20047. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20048. * @param totalVertices Defines the total number of vertices
  20049. * @returns the current mesh
  20050. */
  20051. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20052. return this;
  20053. };
  20054. /**
  20055. * Gets a boolean indicating if specific vertex data is present
  20056. * @param kind defines the vertex data kind to use
  20057. * @returns true is data kind is present
  20058. */
  20059. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20060. return false;
  20061. };
  20062. /**
  20063. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20064. * @returns a BoundingInfo
  20065. */
  20066. AbstractMesh.prototype.getBoundingInfo = function () {
  20067. if (this._masterMesh) {
  20068. return this._masterMesh.getBoundingInfo();
  20069. }
  20070. if (!this._boundingInfo) {
  20071. // this._boundingInfo is being created here
  20072. this._updateBoundingInfo();
  20073. }
  20074. // cannot be null.
  20075. return this._boundingInfo;
  20076. };
  20077. /**
  20078. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20079. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20080. * @returns the current mesh
  20081. */
  20082. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20083. if (includeDescendants === void 0) { includeDescendants = true; }
  20084. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20085. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20086. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20087. if (maxDimension === 0) {
  20088. return this;
  20089. }
  20090. var scale = 1 / maxDimension;
  20091. this.scaling.scaleInPlace(scale);
  20092. return this;
  20093. };
  20094. /**
  20095. * Overwrite the current bounding info
  20096. * @param boundingInfo defines the new bounding info
  20097. * @returns the current mesh
  20098. */
  20099. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20100. this._boundingInfo = boundingInfo;
  20101. return this;
  20102. };
  20103. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20104. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20105. get: function () {
  20106. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20107. },
  20108. enumerable: true,
  20109. configurable: true
  20110. });
  20111. /** @hidden */
  20112. AbstractMesh.prototype._preActivate = function () {
  20113. };
  20114. /** @hidden */
  20115. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20116. };
  20117. /** @hidden */
  20118. AbstractMesh.prototype._activate = function (renderId) {
  20119. this._renderId = renderId;
  20120. };
  20121. /**
  20122. * Gets the current world matrix
  20123. * @returns a Matrix
  20124. */
  20125. AbstractMesh.prototype.getWorldMatrix = function () {
  20126. if (this._masterMesh) {
  20127. return this._masterMesh.getWorldMatrix();
  20128. }
  20129. return _super.prototype.getWorldMatrix.call(this);
  20130. };
  20131. /** @hidden */
  20132. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20133. if (this._masterMesh) {
  20134. return this._masterMesh._getWorldMatrixDeterminant();
  20135. }
  20136. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20137. };
  20138. // ================================== Point of View Movement =================================
  20139. /**
  20140. * Perform relative position change from the point of view of behind the front of the mesh.
  20141. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20142. * Supports definition of mesh facing forward or backward
  20143. * @param amountRight defines the distance on the right axis
  20144. * @param amountUp defines the distance on the up axis
  20145. * @param amountForward defines the distance on the forward axis
  20146. * @returns the current mesh
  20147. */
  20148. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20149. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20150. return this;
  20151. };
  20152. /**
  20153. * Calculate relative position change from the point of view of behind the front of the mesh.
  20154. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20155. * Supports definition of mesh facing forward or backward
  20156. * @param amountRight defines the distance on the right axis
  20157. * @param amountUp defines the distance on the up axis
  20158. * @param amountForward defines the distance on the forward axis
  20159. * @returns the new displacement vector
  20160. */
  20161. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20162. var rotMatrix = new BABYLON.Matrix();
  20163. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20164. rotQuaternion.toRotationMatrix(rotMatrix);
  20165. var translationDelta = BABYLON.Vector3.Zero();
  20166. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20167. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20168. return translationDelta;
  20169. };
  20170. // ================================== Point of View Rotation =================================
  20171. /**
  20172. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20173. * Supports definition of mesh facing forward or backward
  20174. * @param flipBack defines the flip
  20175. * @param twirlClockwise defines the twirl
  20176. * @param tiltRight defines the tilt
  20177. * @returns the current mesh
  20178. */
  20179. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20180. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20181. return this;
  20182. };
  20183. /**
  20184. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20185. * Supports definition of mesh facing forward or backward.
  20186. * @param flipBack defines the flip
  20187. * @param twirlClockwise defines the twirl
  20188. * @param tiltRight defines the tilt
  20189. * @returns the new rotation vector
  20190. */
  20191. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20192. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20193. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20194. };
  20195. /**
  20196. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20197. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20198. * @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
  20199. * @returns the new bounding vectors
  20200. */
  20201. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20202. if (includeDescendants === void 0) { includeDescendants = true; }
  20203. if (predicate === void 0) { predicate = null; }
  20204. // Ensures that all world matrix will be recomputed.
  20205. this.getScene().incrementRenderId();
  20206. this.computeWorldMatrix(true);
  20207. var min;
  20208. var max;
  20209. var boundingInfo = this.getBoundingInfo();
  20210. if (!this.subMeshes) {
  20211. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20212. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20213. }
  20214. else {
  20215. min = boundingInfo.boundingBox.minimumWorld;
  20216. max = boundingInfo.boundingBox.maximumWorld;
  20217. }
  20218. if (includeDescendants) {
  20219. var descendants = this.getDescendants(false);
  20220. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20221. var descendant = descendants_1[_i];
  20222. var childMesh = descendant;
  20223. childMesh.computeWorldMatrix(true);
  20224. // Filters meshes based on custom predicate function.
  20225. if (predicate && !predicate(childMesh)) {
  20226. continue;
  20227. }
  20228. //make sure we have the needed params to get mix and max
  20229. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20230. continue;
  20231. }
  20232. var childBoundingInfo = childMesh.getBoundingInfo();
  20233. var boundingBox = childBoundingInfo.boundingBox;
  20234. var minBox = boundingBox.minimumWorld;
  20235. var maxBox = boundingBox.maximumWorld;
  20236. BABYLON.Tools.CheckExtends(minBox, min, max);
  20237. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20238. }
  20239. }
  20240. return {
  20241. min: min,
  20242. max: max
  20243. };
  20244. };
  20245. /** @hidden */
  20246. AbstractMesh.prototype._updateBoundingInfo = function () {
  20247. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20248. this._boundingInfo.update(this.worldMatrixFromCache);
  20249. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20250. return this;
  20251. };
  20252. /** @hidden */
  20253. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20254. if (!this.subMeshes) {
  20255. return this;
  20256. }
  20257. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20258. var subMesh = this.subMeshes[subIndex];
  20259. if (!subMesh.IsGlobal) {
  20260. subMesh.updateBoundingInfo(matrix);
  20261. }
  20262. }
  20263. return this;
  20264. };
  20265. /** @hidden */
  20266. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20267. // Bounding info
  20268. this._updateBoundingInfo();
  20269. };
  20270. /**
  20271. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20272. * A mesh is in the frustum if its bounding box intersects the frustum
  20273. * @param frustumPlanes defines the frustum to test
  20274. * @returns true if the mesh is in the frustum planes
  20275. */
  20276. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20277. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20278. };
  20279. /**
  20280. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20281. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20282. * @param frustumPlanes defines the frustum to test
  20283. * @returns true if the mesh is completely in the frustum planes
  20284. */
  20285. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20286. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20287. };
  20288. /**
  20289. * True if the mesh intersects another mesh or a SolidParticle object
  20290. * @param mesh defines a target mesh or SolidParticle to test
  20291. * @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)
  20292. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20293. * @returns true if there is an intersection
  20294. */
  20295. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20296. if (precise === void 0) { precise = false; }
  20297. if (!this._boundingInfo || !mesh._boundingInfo) {
  20298. return false;
  20299. }
  20300. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20301. return true;
  20302. }
  20303. if (includeDescendants) {
  20304. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20305. var child = _a[_i];
  20306. if (child.intersectsMesh(mesh, precise, true)) {
  20307. return true;
  20308. }
  20309. }
  20310. }
  20311. return false;
  20312. };
  20313. /**
  20314. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20315. * @param point defines the point to test
  20316. * @returns true if there is an intersection
  20317. */
  20318. AbstractMesh.prototype.intersectsPoint = function (point) {
  20319. if (!this._boundingInfo) {
  20320. return false;
  20321. }
  20322. return this._boundingInfo.intersectsPoint(point);
  20323. };
  20324. /**
  20325. * Gets the current physics impostor
  20326. * @see http://doc.babylonjs.com/features/physics_engine
  20327. * @returns a physics impostor or null
  20328. */
  20329. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20330. return this.physicsImpostor;
  20331. };
  20332. /**
  20333. * Gets the position of the current mesh in camera space
  20334. * @param camera defines the camera to use
  20335. * @returns a position
  20336. */
  20337. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20338. if (camera === void 0) { camera = null; }
  20339. if (!camera) {
  20340. camera = this.getScene().activeCamera;
  20341. }
  20342. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20343. };
  20344. /**
  20345. * Returns the distance from the mesh to the active camera
  20346. * @param camera defines the camera to use
  20347. * @returns the distance
  20348. */
  20349. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20350. if (camera === void 0) { camera = null; }
  20351. if (!camera) {
  20352. camera = this.getScene().activeCamera;
  20353. }
  20354. return this.absolutePosition.subtract(camera.position).length();
  20355. };
  20356. /**
  20357. * Apply a physic impulse to the mesh
  20358. * @param force defines the force to apply
  20359. * @param contactPoint defines where to apply the force
  20360. * @returns the current mesh
  20361. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20362. */
  20363. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20364. if (!this.physicsImpostor) {
  20365. return this;
  20366. }
  20367. this.physicsImpostor.applyImpulse(force, contactPoint);
  20368. return this;
  20369. };
  20370. /**
  20371. * Creates a physic joint between two meshes
  20372. * @param otherMesh defines the other mesh to use
  20373. * @param pivot1 defines the pivot to use on this mesh
  20374. * @param pivot2 defines the pivot to use on the other mesh
  20375. * @param options defines additional options (can be plugin dependent)
  20376. * @returns the current mesh
  20377. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20378. */
  20379. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20380. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20381. return this;
  20382. }
  20383. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20384. mainPivot: pivot1,
  20385. connectedPivot: pivot2,
  20386. nativeParams: options
  20387. });
  20388. return this;
  20389. };
  20390. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20391. // Collisions
  20392. /**
  20393. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20394. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20395. */
  20396. get: function () {
  20397. return this._checkCollisions;
  20398. },
  20399. set: function (collisionEnabled) {
  20400. this._checkCollisions = collisionEnabled;
  20401. if (this.getScene().workerCollisions) {
  20402. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20403. }
  20404. },
  20405. enumerable: true,
  20406. configurable: true
  20407. });
  20408. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20409. /**
  20410. * Gets Collider object used to compute collisions (not physics)
  20411. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20412. */
  20413. get: function () {
  20414. return this._collider;
  20415. },
  20416. enumerable: true,
  20417. configurable: true
  20418. });
  20419. /**
  20420. * Move the mesh using collision engine
  20421. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20422. * @param displacement defines the requested displacement vector
  20423. * @returns the current mesh
  20424. */
  20425. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20426. var globalPosition = this.getAbsolutePosition();
  20427. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20428. if (!this._collider) {
  20429. this._collider = new BABYLON.Collider();
  20430. }
  20431. this._collider._radius = this.ellipsoid;
  20432. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20433. return this;
  20434. };
  20435. // Submeshes octree
  20436. /**
  20437. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20438. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20439. * @param maxCapacity defines the maximum size of each block (64 by default)
  20440. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20441. * @returns the new octree
  20442. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20443. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20444. */
  20445. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20446. if (maxCapacity === void 0) { maxCapacity = 64; }
  20447. if (maxDepth === void 0) { maxDepth = 2; }
  20448. if (!this._submeshesOctree) {
  20449. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20450. }
  20451. this.computeWorldMatrix(true);
  20452. var boundingInfo = this.getBoundingInfo();
  20453. // Update octree
  20454. var bbox = boundingInfo.boundingBox;
  20455. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20456. return this._submeshesOctree;
  20457. };
  20458. // Collisions
  20459. /** @hidden */
  20460. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20461. this._generatePointsArray();
  20462. if (!this._positions) {
  20463. return this;
  20464. }
  20465. // Transformation
  20466. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20467. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20468. subMesh._lastColliderWorldVertices = [];
  20469. subMesh._trianglePlanes = [];
  20470. var start = subMesh.verticesStart;
  20471. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20472. for (var i = start; i < end; i++) {
  20473. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20474. }
  20475. }
  20476. // Collide
  20477. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20478. if (collider.collisionFound) {
  20479. collider.collidedMesh = this;
  20480. }
  20481. return this;
  20482. };
  20483. /** @hidden */
  20484. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20485. var subMeshes;
  20486. var len;
  20487. // Octrees
  20488. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20489. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20490. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20491. len = intersections.length;
  20492. subMeshes = intersections.data;
  20493. }
  20494. else {
  20495. subMeshes = this.subMeshes;
  20496. len = subMeshes.length;
  20497. }
  20498. for (var index = 0; index < len; index++) {
  20499. var subMesh = subMeshes[index];
  20500. // Bounding test
  20501. if (len > 1 && !subMesh._checkCollision(collider))
  20502. continue;
  20503. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20504. }
  20505. return this;
  20506. };
  20507. /** @hidden */
  20508. AbstractMesh.prototype._checkCollision = function (collider) {
  20509. // Bounding box test
  20510. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20511. return this;
  20512. // Transformation matrix
  20513. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20514. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20515. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20516. return this;
  20517. };
  20518. // Picking
  20519. /** @hidden */
  20520. AbstractMesh.prototype._generatePointsArray = function () {
  20521. return false;
  20522. };
  20523. /**
  20524. * Checks if the passed Ray intersects with the mesh
  20525. * @param ray defines the ray to use
  20526. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20527. * @returns the picking info
  20528. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20529. */
  20530. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20531. var pickingInfo = new BABYLON.PickingInfo();
  20532. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20533. return pickingInfo;
  20534. }
  20535. if (!this._generatePointsArray()) {
  20536. return pickingInfo;
  20537. }
  20538. var intersectInfo = null;
  20539. // Octrees
  20540. var subMeshes;
  20541. var len;
  20542. if (this._submeshesOctree && this.useOctreeForPicking) {
  20543. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20544. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20545. len = intersections.length;
  20546. subMeshes = intersections.data;
  20547. }
  20548. else {
  20549. subMeshes = this.subMeshes;
  20550. len = subMeshes.length;
  20551. }
  20552. for (var index = 0; index < len; index++) {
  20553. var subMesh = subMeshes[index];
  20554. // Bounding test
  20555. if (len > 1 && !subMesh.canIntersects(ray))
  20556. continue;
  20557. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20558. if (currentIntersectInfo) {
  20559. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20560. intersectInfo = currentIntersectInfo;
  20561. intersectInfo.subMeshId = index;
  20562. if (fastCheck) {
  20563. break;
  20564. }
  20565. }
  20566. }
  20567. }
  20568. if (intersectInfo) {
  20569. // Get picked point
  20570. var world = this.getWorldMatrix();
  20571. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20572. var direction = ray.direction.clone();
  20573. direction = direction.scale(intersectInfo.distance);
  20574. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20575. var pickedPoint = worldOrigin.add(worldDirection);
  20576. // Return result
  20577. pickingInfo.hit = true;
  20578. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20579. pickingInfo.pickedPoint = pickedPoint;
  20580. pickingInfo.pickedMesh = this;
  20581. pickingInfo.bu = intersectInfo.bu || 0;
  20582. pickingInfo.bv = intersectInfo.bv || 0;
  20583. pickingInfo.faceId = intersectInfo.faceId;
  20584. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20585. return pickingInfo;
  20586. }
  20587. return pickingInfo;
  20588. };
  20589. /**
  20590. * Clones the current mesh
  20591. * @param name defines the mesh name
  20592. * @param newParent defines the new mesh parent
  20593. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20594. * @returns the new mesh
  20595. */
  20596. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20597. return null;
  20598. };
  20599. /**
  20600. * Disposes all the submeshes of the current meshnp
  20601. * @returns the current mesh
  20602. */
  20603. AbstractMesh.prototype.releaseSubMeshes = function () {
  20604. if (this.subMeshes) {
  20605. while (this.subMeshes.length) {
  20606. this.subMeshes[0].dispose();
  20607. }
  20608. }
  20609. else {
  20610. this.subMeshes = new Array();
  20611. }
  20612. return this;
  20613. };
  20614. /**
  20615. * Releases resources associated with this abstract mesh.
  20616. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20617. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20618. */
  20619. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20620. var _this = this;
  20621. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20622. var index;
  20623. // Smart Array Retainers.
  20624. this.getScene().freeActiveMeshes();
  20625. this.getScene().freeRenderingGroups();
  20626. // Action manager
  20627. if (this.actionManager !== undefined && this.actionManager !== null) {
  20628. this.actionManager.dispose();
  20629. this.actionManager = null;
  20630. }
  20631. // Skeleton
  20632. this._skeleton = null;
  20633. // Physics
  20634. if (this.physicsImpostor) {
  20635. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20636. }
  20637. // Intersections in progress
  20638. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20639. var other = this._intersectionsInProgress[index];
  20640. var pos = other._intersectionsInProgress.indexOf(this);
  20641. other._intersectionsInProgress.splice(pos, 1);
  20642. }
  20643. this._intersectionsInProgress = [];
  20644. // Lights
  20645. var lights = this.getScene().lights;
  20646. lights.forEach(function (light) {
  20647. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20648. if (meshIndex !== -1) {
  20649. light.includedOnlyMeshes.splice(meshIndex, 1);
  20650. }
  20651. meshIndex = light.excludedMeshes.indexOf(_this);
  20652. if (meshIndex !== -1) {
  20653. light.excludedMeshes.splice(meshIndex, 1);
  20654. }
  20655. // Shadow generators
  20656. var generator = light.getShadowGenerator();
  20657. if (generator) {
  20658. var shadowMap = generator.getShadowMap();
  20659. if (shadowMap && shadowMap.renderList) {
  20660. meshIndex = shadowMap.renderList.indexOf(_this);
  20661. if (meshIndex !== -1) {
  20662. shadowMap.renderList.splice(meshIndex, 1);
  20663. }
  20664. }
  20665. }
  20666. });
  20667. // Edges
  20668. if (this._edgesRenderer) {
  20669. this._edgesRenderer.dispose();
  20670. this._edgesRenderer = null;
  20671. }
  20672. // SubMeshes
  20673. if (this.getClassName() !== "InstancedMesh") {
  20674. this.releaseSubMeshes();
  20675. }
  20676. // Octree
  20677. var sceneOctree = this.getScene().selectionOctree;
  20678. if (sceneOctree !== undefined && sceneOctree !== null) {
  20679. var index = sceneOctree.dynamicContent.indexOf(this);
  20680. if (index !== -1) {
  20681. sceneOctree.dynamicContent.splice(index, 1);
  20682. }
  20683. }
  20684. // Query
  20685. var engine = this.getScene().getEngine();
  20686. if (this._occlusionQuery) {
  20687. this._isOcclusionQueryInProgress = false;
  20688. engine.deleteQuery(this._occlusionQuery);
  20689. this._occlusionQuery = null;
  20690. }
  20691. // Engine
  20692. engine.wipeCaches();
  20693. // Remove from scene
  20694. this.getScene().removeMesh(this);
  20695. if (disposeMaterialAndTextures) {
  20696. if (this.material) {
  20697. this.material.dispose(false, true);
  20698. }
  20699. }
  20700. if (!doNotRecurse) {
  20701. // Particles
  20702. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20703. if (this.getScene().particleSystems[index].emitter === this) {
  20704. this.getScene().particleSystems[index].dispose();
  20705. index--;
  20706. }
  20707. }
  20708. }
  20709. // facet data
  20710. if (this._facetDataEnabled) {
  20711. this.disableFacetData();
  20712. }
  20713. this.onAfterWorldMatrixUpdateObservable.clear();
  20714. this.onCollideObservable.clear();
  20715. this.onCollisionPositionChangeObservable.clear();
  20716. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20717. };
  20718. /**
  20719. * Adds the passed mesh as a child to the current mesh
  20720. * @param mesh defines the child mesh
  20721. * @returns the current mesh
  20722. */
  20723. AbstractMesh.prototype.addChild = function (mesh) {
  20724. mesh.setParent(this);
  20725. return this;
  20726. };
  20727. /**
  20728. * Removes the passed mesh from the current mesh children list
  20729. * @param mesh defines the child mesh
  20730. * @returns the current mesh
  20731. */
  20732. AbstractMesh.prototype.removeChild = function (mesh) {
  20733. mesh.setParent(null);
  20734. return this;
  20735. };
  20736. // Facet data
  20737. /** @hidden */
  20738. AbstractMesh.prototype._initFacetData = function () {
  20739. if (!this._facetNormals) {
  20740. this._facetNormals = new Array();
  20741. }
  20742. if (!this._facetPositions) {
  20743. this._facetPositions = new Array();
  20744. }
  20745. if (!this._facetPartitioning) {
  20746. this._facetPartitioning = new Array();
  20747. }
  20748. this._facetNb = (this.getIndices().length / 3) | 0;
  20749. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20750. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20751. for (var f = 0; f < this._facetNb; f++) {
  20752. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20753. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20754. }
  20755. this._facetDataEnabled = true;
  20756. return this;
  20757. };
  20758. /**
  20759. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20760. * This method can be called within the render loop.
  20761. * 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
  20762. * @returns the current mesh
  20763. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20764. */
  20765. AbstractMesh.prototype.updateFacetData = function () {
  20766. if (!this._facetDataEnabled) {
  20767. this._initFacetData();
  20768. }
  20769. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20770. var indices = this.getIndices();
  20771. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20772. var bInfo = this.getBoundingInfo();
  20773. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20774. // init arrays, matrix and sort function on first call
  20775. this._facetDepthSortEnabled = true;
  20776. if (indices instanceof Uint16Array) {
  20777. this._depthSortedIndices = new Uint16Array(indices);
  20778. }
  20779. else if (indices instanceof Uint32Array) {
  20780. this._depthSortedIndices = new Uint32Array(indices);
  20781. }
  20782. else {
  20783. var needs32bits = false;
  20784. for (var i = 0; i < indices.length; i++) {
  20785. if (indices[i] > 65535) {
  20786. needs32bits = true;
  20787. break;
  20788. }
  20789. }
  20790. if (needs32bits) {
  20791. this._depthSortedIndices = new Uint32Array(indices);
  20792. }
  20793. else {
  20794. this._depthSortedIndices = new Uint16Array(indices);
  20795. }
  20796. }
  20797. this._facetDepthSortFunction = function (f1, f2) {
  20798. return (f2.sqDistance - f1.sqDistance);
  20799. };
  20800. if (!this._facetDepthSortFrom) {
  20801. var camera = this.getScene().activeCamera;
  20802. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20803. }
  20804. this._depthSortedFacets = [];
  20805. for (var f = 0; f < this._facetNb; f++) {
  20806. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20807. this._depthSortedFacets.push(depthSortedFacet);
  20808. }
  20809. this._invertedMatrix = BABYLON.Matrix.Identity();
  20810. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20811. }
  20812. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20813. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20814. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20815. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20816. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20817. this._subDiv.max = this._partitioningSubdivisions;
  20818. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20819. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20820. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20821. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20822. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20823. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20824. // set the parameters for ComputeNormals()
  20825. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20826. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20827. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20828. this._facetParameters.bInfo = bInfo;
  20829. this._facetParameters.bbSize = this._bbSize;
  20830. this._facetParameters.subDiv = this._subDiv;
  20831. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20832. this._facetParameters.depthSort = this._facetDepthSort;
  20833. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20834. this.computeWorldMatrix(true);
  20835. this._worldMatrix.invertToRef(this._invertedMatrix);
  20836. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20837. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20838. }
  20839. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20840. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20841. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20842. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20843. var l = (this._depthSortedIndices.length / 3) | 0;
  20844. for (var f = 0; f < l; f++) {
  20845. var sind = this._depthSortedFacets[f].ind;
  20846. this._depthSortedIndices[f * 3] = indices[sind];
  20847. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20848. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20849. }
  20850. this.updateIndices(this._depthSortedIndices);
  20851. }
  20852. return this;
  20853. };
  20854. /**
  20855. * Returns the facetLocalNormals array.
  20856. * The normals are expressed in the mesh local spac
  20857. * @returns an array of Vector3
  20858. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20859. */
  20860. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20861. if (!this._facetNormals) {
  20862. this.updateFacetData();
  20863. }
  20864. return this._facetNormals;
  20865. };
  20866. /**
  20867. * Returns the facetLocalPositions array.
  20868. * The facet positions are expressed in the mesh local space
  20869. * @returns an array of Vector3
  20870. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20871. */
  20872. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20873. if (!this._facetPositions) {
  20874. this.updateFacetData();
  20875. }
  20876. return this._facetPositions;
  20877. };
  20878. /**
  20879. * Returns the facetLocalPartioning array
  20880. * @returns an array of array of numbers
  20881. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20882. */
  20883. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20884. if (!this._facetPartitioning) {
  20885. this.updateFacetData();
  20886. }
  20887. return this._facetPartitioning;
  20888. };
  20889. /**
  20890. * Returns the i-th facet position in the world system.
  20891. * This method allocates a new Vector3 per call
  20892. * @param i defines the facet index
  20893. * @returns a new Vector3
  20894. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20895. */
  20896. AbstractMesh.prototype.getFacetPosition = function (i) {
  20897. var pos = BABYLON.Vector3.Zero();
  20898. this.getFacetPositionToRef(i, pos);
  20899. return pos;
  20900. };
  20901. /**
  20902. * Sets the reference Vector3 with the i-th facet position in the world system
  20903. * @param i defines the facet index
  20904. * @param ref defines the target vector
  20905. * @returns the current mesh
  20906. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20907. */
  20908. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20909. var localPos = (this.getFacetLocalPositions())[i];
  20910. var world = this.getWorldMatrix();
  20911. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20912. return this;
  20913. };
  20914. /**
  20915. * Returns the i-th facet normal in the world system.
  20916. * This method allocates a new Vector3 per call
  20917. * @param i defines the facet index
  20918. * @returns a new Vector3
  20919. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20920. */
  20921. AbstractMesh.prototype.getFacetNormal = function (i) {
  20922. var norm = BABYLON.Vector3.Zero();
  20923. this.getFacetNormalToRef(i, norm);
  20924. return norm;
  20925. };
  20926. /**
  20927. * Sets the reference Vector3 with the i-th facet normal in the world system
  20928. * @param i defines the facet index
  20929. * @param ref defines the target vector
  20930. * @returns the current mesh
  20931. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20932. */
  20933. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20934. var localNorm = (this.getFacetLocalNormals())[i];
  20935. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20936. return this;
  20937. };
  20938. /**
  20939. * 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)
  20940. * @param x defines x coordinate
  20941. * @param y defines y coordinate
  20942. * @param z defines z coordinate
  20943. * @returns the array of facet indexes
  20944. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20945. */
  20946. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20947. var bInfo = this.getBoundingInfo();
  20948. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20949. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20950. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20951. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20952. return null;
  20953. }
  20954. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20955. };
  20956. /**
  20957. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20958. * @param projected sets as the (x,y,z) world projection on the facet
  20959. * @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
  20960. * @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
  20961. * @param x defines x coordinate
  20962. * @param y defines y coordinate
  20963. * @param z defines z coordinate
  20964. * @returns the face index if found (or null instead)
  20965. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20966. */
  20967. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20968. if (checkFace === void 0) { checkFace = false; }
  20969. if (facing === void 0) { facing = true; }
  20970. var world = this.getWorldMatrix();
  20971. var invMat = BABYLON.Tmp.Matrix[5];
  20972. world.invertToRef(invMat);
  20973. var invVect = BABYLON.Tmp.Vector3[8];
  20974. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20975. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20976. if (projected) {
  20977. // tranform the local computed projected vector to world coordinates
  20978. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20979. }
  20980. return closest;
  20981. };
  20982. /**
  20983. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  20984. * @param projected sets as the (x,y,z) local projection on the facet
  20985. * @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
  20986. * @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
  20987. * @param x defines x coordinate
  20988. * @param y defines y coordinate
  20989. * @param z defines z coordinate
  20990. * @returns the face index if found (or null instead)
  20991. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20992. */
  20993. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20994. if (checkFace === void 0) { checkFace = false; }
  20995. if (facing === void 0) { facing = true; }
  20996. var closest = null;
  20997. var tmpx = 0.0;
  20998. var tmpy = 0.0;
  20999. var tmpz = 0.0;
  21000. var d = 0.0; // tmp dot facet normal * facet position
  21001. var t0 = 0.0;
  21002. var projx = 0.0;
  21003. var projy = 0.0;
  21004. var projz = 0.0;
  21005. // Get all the facets in the same partitioning block than (x, y, z)
  21006. var facetPositions = this.getFacetLocalPositions();
  21007. var facetNormals = this.getFacetLocalNormals();
  21008. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21009. if (!facetsInBlock) {
  21010. return null;
  21011. }
  21012. // Get the closest facet to (x, y, z)
  21013. var shortest = Number.MAX_VALUE; // init distance vars
  21014. var tmpDistance = shortest;
  21015. var fib; // current facet in the block
  21016. var norm; // current facet normal
  21017. var p0; // current facet barycenter position
  21018. // loop on all the facets in the current partitioning block
  21019. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21020. fib = facetsInBlock[idx];
  21021. norm = facetNormals[fib];
  21022. p0 = facetPositions[fib];
  21023. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21024. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21025. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21026. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21027. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21028. projx = x + norm.x * t0;
  21029. projy = y + norm.y * t0;
  21030. projz = z + norm.z * t0;
  21031. tmpx = projx - x;
  21032. tmpy = projy - y;
  21033. tmpz = projz - z;
  21034. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21035. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21036. shortest = tmpDistance;
  21037. closest = fib;
  21038. if (projected) {
  21039. projected.x = projx;
  21040. projected.y = projy;
  21041. projected.z = projz;
  21042. }
  21043. }
  21044. }
  21045. }
  21046. return closest;
  21047. };
  21048. /**
  21049. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21050. * @returns the parameters
  21051. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21052. */
  21053. AbstractMesh.prototype.getFacetDataParameters = function () {
  21054. return this._facetParameters;
  21055. };
  21056. /**
  21057. * Disables the feature FacetData and frees the related memory
  21058. * @returns the current mesh
  21059. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21060. */
  21061. AbstractMesh.prototype.disableFacetData = function () {
  21062. if (this._facetDataEnabled) {
  21063. this._facetDataEnabled = false;
  21064. this._facetPositions = new Array();
  21065. this._facetNormals = new Array();
  21066. this._facetPartitioning = new Array();
  21067. this._facetParameters = null;
  21068. this._depthSortedIndices = new Uint32Array(0);
  21069. }
  21070. return this;
  21071. };
  21072. /**
  21073. * Updates the AbstractMesh indices array
  21074. * @param indices defines the data source
  21075. * @returns the current mesh
  21076. */
  21077. AbstractMesh.prototype.updateIndices = function (indices) {
  21078. return this;
  21079. };
  21080. /**
  21081. * Creates new normals data for the mesh
  21082. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21083. * @returns the current mesh
  21084. */
  21085. AbstractMesh.prototype.createNormals = function (updatable) {
  21086. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21087. var indices = this.getIndices();
  21088. var normals;
  21089. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21090. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21091. }
  21092. else {
  21093. normals = [];
  21094. }
  21095. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21096. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21097. return this;
  21098. };
  21099. /**
  21100. * Align the mesh with a normal
  21101. * @param normal defines the normal to use
  21102. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21103. * @returns the current mesh
  21104. */
  21105. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21106. if (!upDirection) {
  21107. upDirection = BABYLON.Axis.Y;
  21108. }
  21109. var axisX = BABYLON.Tmp.Vector3[0];
  21110. var axisZ = BABYLON.Tmp.Vector3[1];
  21111. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21112. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21113. if (this.rotationQuaternion) {
  21114. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21115. }
  21116. else {
  21117. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21118. }
  21119. return this;
  21120. };
  21121. /** @hidden */
  21122. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21123. this._isOccluded = false;
  21124. };
  21125. /** No occlusion */
  21126. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21127. /** Occlusion set to optimisitic */
  21128. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21129. /** Occlusion set to strict */
  21130. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21131. /** Use an accurante occlusion algorithm */
  21132. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21133. /** Use a conservative occlusion algorithm */
  21134. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21135. return AbstractMesh;
  21136. }(BABYLON.TransformNode));
  21137. BABYLON.AbstractMesh = AbstractMesh;
  21138. })(BABYLON || (BABYLON = {}));
  21139. //# sourceMappingURL=babylon.abstractMesh.js.map
  21140. var BABYLON;
  21141. (function (BABYLON) {
  21142. /**
  21143. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21144. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21145. * 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.
  21146. */
  21147. var Light = /** @class */ (function (_super) {
  21148. __extends(Light, _super);
  21149. /**
  21150. * Creates a Light object in the scene.
  21151. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21152. * @param name The firendly name of the light
  21153. * @param scene The scene the light belongs too
  21154. */
  21155. function Light(name, scene) {
  21156. var _this = _super.call(this, name, scene) || this;
  21157. /**
  21158. * Diffuse gives the basic color to an object.
  21159. */
  21160. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21161. /**
  21162. * Specular produces a highlight color on an object.
  21163. * Note: This is note affecting PBR materials.
  21164. */
  21165. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21166. /**
  21167. * Strength of the light.
  21168. * Note: By default it is define in the framework own unit.
  21169. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21170. */
  21171. _this.intensity = 1.0;
  21172. /**
  21173. * Defines how far from the source the light is impacting in scene units.
  21174. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21175. */
  21176. _this.range = Number.MAX_VALUE;
  21177. /**
  21178. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21179. * of light.
  21180. */
  21181. _this._photometricScale = 1.0;
  21182. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21183. _this._radius = 0.00001;
  21184. /**
  21185. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21186. * exceeding the number allowed of the materials.
  21187. */
  21188. _this.renderPriority = 0;
  21189. _this._shadowEnabled = true;
  21190. _this._excludeWithLayerMask = 0;
  21191. _this._includeOnlyWithLayerMask = 0;
  21192. _this._lightmapMode = 0;
  21193. /**
  21194. * @hidden Internal use only.
  21195. */
  21196. _this._excludedMeshesIds = new Array();
  21197. /**
  21198. * @hidden Internal use only.
  21199. */
  21200. _this._includedOnlyMeshesIds = new Array();
  21201. _this.getScene().addLight(_this);
  21202. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21203. _this._buildUniformLayout();
  21204. _this.includedOnlyMeshes = new Array();
  21205. _this.excludedMeshes = new Array();
  21206. _this._resyncMeshes();
  21207. return _this;
  21208. }
  21209. Object.defineProperty(Light.prototype, "intensityMode", {
  21210. /**
  21211. * Gets the photometric scale used to interpret the intensity.
  21212. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21213. */
  21214. get: function () {
  21215. return this._intensityMode;
  21216. },
  21217. /**
  21218. * Sets the photometric scale used to interpret the intensity.
  21219. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21220. */
  21221. set: function (value) {
  21222. this._intensityMode = value;
  21223. this._computePhotometricScale();
  21224. },
  21225. enumerable: true,
  21226. configurable: true
  21227. });
  21228. ;
  21229. ;
  21230. Object.defineProperty(Light.prototype, "radius", {
  21231. /**
  21232. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21233. */
  21234. get: function () {
  21235. return this._radius;
  21236. },
  21237. /**
  21238. * sets the light radius used by PBR Materials to simulate soft area lights.
  21239. */
  21240. set: function (value) {
  21241. this._radius = value;
  21242. this._computePhotometricScale();
  21243. },
  21244. enumerable: true,
  21245. configurable: true
  21246. });
  21247. ;
  21248. ;
  21249. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21250. /**
  21251. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21252. * the current shadow generator.
  21253. */
  21254. get: function () {
  21255. return this._shadowEnabled;
  21256. },
  21257. /**
  21258. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21259. * the current shadow generator.
  21260. */
  21261. set: function (value) {
  21262. if (this._shadowEnabled === value) {
  21263. return;
  21264. }
  21265. this._shadowEnabled = value;
  21266. this._markMeshesAsLightDirty();
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21272. /**
  21273. * Gets the only meshes impacted by this light.
  21274. */
  21275. get: function () {
  21276. return this._includedOnlyMeshes;
  21277. },
  21278. /**
  21279. * Sets the only meshes impacted by this light.
  21280. */
  21281. set: function (value) {
  21282. this._includedOnlyMeshes = value;
  21283. this._hookArrayForIncludedOnly(value);
  21284. },
  21285. enumerable: true,
  21286. configurable: true
  21287. });
  21288. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21289. /**
  21290. * Gets the meshes not impacted by this light.
  21291. */
  21292. get: function () {
  21293. return this._excludedMeshes;
  21294. },
  21295. /**
  21296. * Sets the meshes not impacted by this light.
  21297. */
  21298. set: function (value) {
  21299. this._excludedMeshes = value;
  21300. this._hookArrayForExcluded(value);
  21301. },
  21302. enumerable: true,
  21303. configurable: true
  21304. });
  21305. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21306. /**
  21307. * Gets the layer id use to find what meshes are not impacted by the light.
  21308. * Inactive if 0
  21309. */
  21310. get: function () {
  21311. return this._excludeWithLayerMask;
  21312. },
  21313. /**
  21314. * Sets the layer id use to find what meshes are not impacted by the light.
  21315. * Inactive if 0
  21316. */
  21317. set: function (value) {
  21318. this._excludeWithLayerMask = value;
  21319. this._resyncMeshes();
  21320. },
  21321. enumerable: true,
  21322. configurable: true
  21323. });
  21324. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21325. /**
  21326. * Gets the layer id use to find what meshes are impacted by the light.
  21327. * Inactive if 0
  21328. */
  21329. get: function () {
  21330. return this._includeOnlyWithLayerMask;
  21331. },
  21332. /**
  21333. * Sets the layer id use to find what meshes are impacted by the light.
  21334. * Inactive if 0
  21335. */
  21336. set: function (value) {
  21337. this._includeOnlyWithLayerMask = value;
  21338. this._resyncMeshes();
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Object.defineProperty(Light.prototype, "lightmapMode", {
  21344. /**
  21345. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21346. */
  21347. get: function () {
  21348. return this._lightmapMode;
  21349. },
  21350. /**
  21351. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21352. */
  21353. set: function (value) {
  21354. if (this._lightmapMode === value) {
  21355. return;
  21356. }
  21357. this._lightmapMode = value;
  21358. this._markMeshesAsLightDirty();
  21359. },
  21360. enumerable: true,
  21361. configurable: true
  21362. });
  21363. /**
  21364. * Returns the string "Light".
  21365. * @returns the class name
  21366. */
  21367. Light.prototype.getClassName = function () {
  21368. return "Light";
  21369. };
  21370. /**
  21371. * Converts the light information to a readable string for debug purpose.
  21372. * @param fullDetails Supports for multiple levels of logging within scene loading
  21373. * @returns the human readable light info
  21374. */
  21375. Light.prototype.toString = function (fullDetails) {
  21376. var ret = "Name: " + this.name;
  21377. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21378. if (this.animations) {
  21379. for (var i = 0; i < this.animations.length; i++) {
  21380. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21381. }
  21382. }
  21383. if (fullDetails) {
  21384. }
  21385. return ret;
  21386. };
  21387. /**
  21388. * Set the enabled state of this node.
  21389. * @param value - the new enabled state
  21390. */
  21391. Light.prototype.setEnabled = function (value) {
  21392. _super.prototype.setEnabled.call(this, value);
  21393. this._resyncMeshes();
  21394. };
  21395. /**
  21396. * Returns the Light associated shadow generator if any.
  21397. * @return the associated shadow generator.
  21398. */
  21399. Light.prototype.getShadowGenerator = function () {
  21400. return this._shadowGenerator;
  21401. };
  21402. /**
  21403. * Returns a Vector3, the absolute light position in the World.
  21404. * @returns the world space position of the light
  21405. */
  21406. Light.prototype.getAbsolutePosition = function () {
  21407. return BABYLON.Vector3.Zero();
  21408. };
  21409. /**
  21410. * Specifies if the light will affect the passed mesh.
  21411. * @param mesh The mesh to test against the light
  21412. * @return true the mesh is affected otherwise, false.
  21413. */
  21414. Light.prototype.canAffectMesh = function (mesh) {
  21415. if (!mesh) {
  21416. return true;
  21417. }
  21418. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21419. return false;
  21420. }
  21421. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21422. return false;
  21423. }
  21424. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21425. return false;
  21426. }
  21427. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21428. return false;
  21429. }
  21430. return true;
  21431. };
  21432. /**
  21433. * Computes and Returns the light World matrix.
  21434. * @returns the world matrix
  21435. */
  21436. Light.prototype.getWorldMatrix = function () {
  21437. this._currentRenderId = this.getScene().getRenderId();
  21438. this._childRenderId = this._currentRenderId;
  21439. var worldMatrix = this._getWorldMatrix();
  21440. if (this.parent && this.parent.getWorldMatrix) {
  21441. if (!this._parentedWorldMatrix) {
  21442. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21443. }
  21444. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21445. this._markSyncedWithParent();
  21446. return this._parentedWorldMatrix;
  21447. }
  21448. return worldMatrix;
  21449. };
  21450. /**
  21451. * Sort function to order lights for rendering.
  21452. * @param a First Light object to compare to second.
  21453. * @param b Second Light object to compare first.
  21454. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21455. */
  21456. Light.CompareLightsPriority = function (a, b) {
  21457. //shadow-casting lights have priority over non-shadow-casting lights
  21458. //the renderPrioirty is a secondary sort criterion
  21459. if (a.shadowEnabled !== b.shadowEnabled) {
  21460. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21461. }
  21462. return b.renderPriority - a.renderPriority;
  21463. };
  21464. /**
  21465. * Releases resources associated with this node.
  21466. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21467. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21468. */
  21469. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21470. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21471. if (this._shadowGenerator) {
  21472. this._shadowGenerator.dispose();
  21473. this._shadowGenerator = null;
  21474. }
  21475. // Animations
  21476. this.getScene().stopAnimation(this);
  21477. // Remove from meshes
  21478. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21479. var mesh = _a[_i];
  21480. mesh._removeLightSource(this);
  21481. }
  21482. this._uniformBuffer.dispose();
  21483. // Remove from scene
  21484. this.getScene().removeLight(this);
  21485. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21486. };
  21487. /**
  21488. * Returns the light type ID (integer).
  21489. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21490. */
  21491. Light.prototype.getTypeID = function () {
  21492. return 0;
  21493. };
  21494. /**
  21495. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21496. * @returns the scaled intensity in intensity mode unit
  21497. */
  21498. Light.prototype.getScaledIntensity = function () {
  21499. return this._photometricScale * this.intensity;
  21500. };
  21501. /**
  21502. * Returns a new Light object, named "name", from the current one.
  21503. * @param name The name of the cloned light
  21504. * @returns the new created light
  21505. */
  21506. Light.prototype.clone = function (name) {
  21507. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21508. if (!constructor) {
  21509. return null;
  21510. }
  21511. return BABYLON.SerializationHelper.Clone(constructor, this);
  21512. };
  21513. /**
  21514. * Serializes the current light into a Serialization object.
  21515. * @returns the serialized object.
  21516. */
  21517. Light.prototype.serialize = function () {
  21518. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21519. // Type
  21520. serializationObject.type = this.getTypeID();
  21521. // Parent
  21522. if (this.parent) {
  21523. serializationObject.parentId = this.parent.id;
  21524. }
  21525. // Inclusion / exclusions
  21526. if (this.excludedMeshes.length > 0) {
  21527. serializationObject.excludedMeshesIds = [];
  21528. this.excludedMeshes.forEach(function (mesh) {
  21529. serializationObject.excludedMeshesIds.push(mesh.id);
  21530. });
  21531. }
  21532. if (this.includedOnlyMeshes.length > 0) {
  21533. serializationObject.includedOnlyMeshesIds = [];
  21534. this.includedOnlyMeshes.forEach(function (mesh) {
  21535. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21536. });
  21537. }
  21538. // Animations
  21539. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21540. serializationObject.ranges = this.serializeAnimationRanges();
  21541. return serializationObject;
  21542. };
  21543. /**
  21544. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21545. * This new light is named "name" and added to the passed scene.
  21546. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21547. * @param name The friendly name of the light
  21548. * @param scene The scene the new light will belong to
  21549. * @returns the constructor function
  21550. */
  21551. Light.GetConstructorFromName = function (type, name, scene) {
  21552. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21553. if (constructorFunc) {
  21554. return constructorFunc;
  21555. }
  21556. // Default to no light for none present once.
  21557. return null;
  21558. };
  21559. /**
  21560. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21561. * @param parsedLight The JSON representation of the light
  21562. * @param scene The scene to create the parsed light in
  21563. * @returns the created light after parsing
  21564. */
  21565. Light.Parse = function (parsedLight, scene) {
  21566. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21567. if (!constructor) {
  21568. return null;
  21569. }
  21570. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21571. // Inclusion / exclusions
  21572. if (parsedLight.excludedMeshesIds) {
  21573. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21574. }
  21575. if (parsedLight.includedOnlyMeshesIds) {
  21576. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21577. }
  21578. // Parent
  21579. if (parsedLight.parentId) {
  21580. light._waitingParentId = parsedLight.parentId;
  21581. }
  21582. // Animations
  21583. if (parsedLight.animations) {
  21584. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21585. var parsedAnimation = parsedLight.animations[animationIndex];
  21586. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21587. }
  21588. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21589. }
  21590. if (parsedLight.autoAnimate) {
  21591. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21592. }
  21593. return light;
  21594. };
  21595. Light.prototype._hookArrayForExcluded = function (array) {
  21596. var _this = this;
  21597. var oldPush = array.push;
  21598. array.push = function () {
  21599. var items = [];
  21600. for (var _i = 0; _i < arguments.length; _i++) {
  21601. items[_i] = arguments[_i];
  21602. }
  21603. var result = oldPush.apply(array, items);
  21604. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21605. var item = items_1[_a];
  21606. item._resyncLighSource(_this);
  21607. }
  21608. return result;
  21609. };
  21610. var oldSplice = array.splice;
  21611. array.splice = function (index, deleteCount) {
  21612. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21613. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21614. var item = deleted_1[_i];
  21615. item._resyncLighSource(_this);
  21616. }
  21617. return deleted;
  21618. };
  21619. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21620. var item = array_1[_i];
  21621. item._resyncLighSource(this);
  21622. }
  21623. };
  21624. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21625. var _this = this;
  21626. var oldPush = array.push;
  21627. array.push = function () {
  21628. var items = [];
  21629. for (var _i = 0; _i < arguments.length; _i++) {
  21630. items[_i] = arguments[_i];
  21631. }
  21632. var result = oldPush.apply(array, items);
  21633. _this._resyncMeshes();
  21634. return result;
  21635. };
  21636. var oldSplice = array.splice;
  21637. array.splice = function (index, deleteCount) {
  21638. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21639. _this._resyncMeshes();
  21640. return deleted;
  21641. };
  21642. this._resyncMeshes();
  21643. };
  21644. Light.prototype._resyncMeshes = function () {
  21645. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21646. var mesh = _a[_i];
  21647. mesh._resyncLighSource(this);
  21648. }
  21649. };
  21650. /**
  21651. * Forces the meshes to update their light related information in their rendering used effects
  21652. * @hidden Internal Use Only
  21653. */
  21654. Light.prototype._markMeshesAsLightDirty = function () {
  21655. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21656. var mesh = _a[_i];
  21657. if (mesh._lightSources.indexOf(this) !== -1) {
  21658. mesh._markSubMeshesAsLightDirty();
  21659. }
  21660. }
  21661. };
  21662. /**
  21663. * Recomputes the cached photometric scale if needed.
  21664. */
  21665. Light.prototype._computePhotometricScale = function () {
  21666. this._photometricScale = this._getPhotometricScale();
  21667. this.getScene().resetCachedMaterial();
  21668. };
  21669. /**
  21670. * Returns the Photometric Scale according to the light type and intensity mode.
  21671. */
  21672. Light.prototype._getPhotometricScale = function () {
  21673. var photometricScale = 0.0;
  21674. var lightTypeID = this.getTypeID();
  21675. //get photometric mode
  21676. var photometricMode = this.intensityMode;
  21677. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21678. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21679. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21680. }
  21681. else {
  21682. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21683. }
  21684. }
  21685. //compute photometric scale
  21686. switch (lightTypeID) {
  21687. case Light.LIGHTTYPEID_POINTLIGHT:
  21688. case Light.LIGHTTYPEID_SPOTLIGHT:
  21689. switch (photometricMode) {
  21690. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21691. photometricScale = 1.0 / (4.0 * Math.PI);
  21692. break;
  21693. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21694. photometricScale = 1.0;
  21695. break;
  21696. case Light.INTENSITYMODE_LUMINANCE:
  21697. photometricScale = this.radius * this.radius;
  21698. break;
  21699. }
  21700. break;
  21701. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21702. switch (photometricMode) {
  21703. case Light.INTENSITYMODE_ILLUMINANCE:
  21704. photometricScale = 1.0;
  21705. break;
  21706. case Light.INTENSITYMODE_LUMINANCE:
  21707. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21708. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21709. var apexAngleRadians = this.radius;
  21710. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21711. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21712. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21713. photometricScale = solidAngle;
  21714. break;
  21715. }
  21716. break;
  21717. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21718. // No fall off in hemisperic light.
  21719. photometricScale = 1.0;
  21720. break;
  21721. }
  21722. return photometricScale;
  21723. };
  21724. /**
  21725. * Reorder the light in the scene according to their defined priority.
  21726. * @hidden Internal Use Only
  21727. */
  21728. Light.prototype._reorderLightsInScene = function () {
  21729. var scene = this.getScene();
  21730. if (this._renderPriority != 0) {
  21731. scene.requireLightSorting = true;
  21732. }
  21733. this.getScene().sortLightsByPriority();
  21734. };
  21735. //lightmapMode Consts
  21736. /**
  21737. * If every light affecting the material is in this lightmapMode,
  21738. * material.lightmapTexture adds or multiplies
  21739. * (depends on material.useLightmapAsShadowmap)
  21740. * after every other light calculations.
  21741. */
  21742. Light.LIGHTMAP_DEFAULT = 0;
  21743. /**
  21744. * material.lightmapTexture as only diffuse lighting from this light
  21745. * adds only specular lighting from this light
  21746. * adds dynamic shadows
  21747. */
  21748. Light.LIGHTMAP_SPECULAR = 1;
  21749. /**
  21750. * material.lightmapTexture as only lighting
  21751. * no light calculation from this light
  21752. * only adds dynamic shadows from this light
  21753. */
  21754. Light.LIGHTMAP_SHADOWSONLY = 2;
  21755. // Intensity Mode Consts
  21756. /**
  21757. * Each light type uses the default quantity according to its type:
  21758. * point/spot lights use luminous intensity
  21759. * directional lights use illuminance
  21760. */
  21761. Light.INTENSITYMODE_AUTOMATIC = 0;
  21762. /**
  21763. * lumen (lm)
  21764. */
  21765. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21766. /**
  21767. * candela (lm/sr)
  21768. */
  21769. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21770. /**
  21771. * lux (lm/m^2)
  21772. */
  21773. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21774. /**
  21775. * nit (cd/m^2)
  21776. */
  21777. Light.INTENSITYMODE_LUMINANCE = 4;
  21778. // Light types ids const.
  21779. /**
  21780. * Light type const id of the point light.
  21781. */
  21782. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21783. /**
  21784. * Light type const id of the directional light.
  21785. */
  21786. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21787. /**
  21788. * Light type const id of the spot light.
  21789. */
  21790. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21791. /**
  21792. * Light type const id of the hemispheric light.
  21793. */
  21794. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21795. __decorate([
  21796. BABYLON.serializeAsColor3()
  21797. ], Light.prototype, "diffuse", void 0);
  21798. __decorate([
  21799. BABYLON.serializeAsColor3()
  21800. ], Light.prototype, "specular", void 0);
  21801. __decorate([
  21802. BABYLON.serialize()
  21803. ], Light.prototype, "intensity", void 0);
  21804. __decorate([
  21805. BABYLON.serialize()
  21806. ], Light.prototype, "range", void 0);
  21807. __decorate([
  21808. BABYLON.serialize()
  21809. ], Light.prototype, "intensityMode", null);
  21810. __decorate([
  21811. BABYLON.serialize()
  21812. ], Light.prototype, "radius", null);
  21813. __decorate([
  21814. BABYLON.serialize()
  21815. ], Light.prototype, "_renderPriority", void 0);
  21816. __decorate([
  21817. BABYLON.expandToProperty("_reorderLightsInScene")
  21818. ], Light.prototype, "renderPriority", void 0);
  21819. __decorate([
  21820. BABYLON.serialize("shadowEnabled")
  21821. ], Light.prototype, "_shadowEnabled", void 0);
  21822. __decorate([
  21823. BABYLON.serialize("excludeWithLayerMask")
  21824. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21825. __decorate([
  21826. BABYLON.serialize("includeOnlyWithLayerMask")
  21827. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21828. __decorate([
  21829. BABYLON.serialize("lightmapMode")
  21830. ], Light.prototype, "_lightmapMode", void 0);
  21831. return Light;
  21832. }(BABYLON.Node));
  21833. BABYLON.Light = Light;
  21834. })(BABYLON || (BABYLON = {}));
  21835. //# sourceMappingURL=babylon.light.js.map
  21836. var BABYLON;
  21837. (function (BABYLON) {
  21838. var Camera = /** @class */ (function (_super) {
  21839. __extends(Camera, _super);
  21840. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21841. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21842. var _this = _super.call(this, name, scene) || this;
  21843. /**
  21844. * The vector the camera should consider as up.
  21845. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21846. */
  21847. _this.upVector = BABYLON.Vector3.Up();
  21848. _this.orthoLeft = null;
  21849. _this.orthoRight = null;
  21850. _this.orthoBottom = null;
  21851. _this.orthoTop = null;
  21852. /**
  21853. * FOV is set in Radians. (default is 0.8)
  21854. */
  21855. _this.fov = 0.8;
  21856. _this.minZ = 1;
  21857. _this.maxZ = 10000.0;
  21858. _this.inertia = 0.9;
  21859. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21860. _this.isIntermediate = false;
  21861. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21862. /**
  21863. * Restricts the camera to viewing objects with the same layerMask.
  21864. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21865. */
  21866. _this.layerMask = 0x0FFFFFFF;
  21867. /**
  21868. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21869. */
  21870. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21871. // Camera rig members
  21872. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21873. _this._rigCameras = new Array();
  21874. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21875. _this._skipRendering = false;
  21876. _this.customRenderTargets = new Array();
  21877. // Observables
  21878. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21879. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21880. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21881. _this.onRestoreStateObservable = new BABYLON.Observable();
  21882. // Cache
  21883. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21884. _this._projectionMatrix = new BABYLON.Matrix();
  21885. _this._doNotComputeProjectionMatrix = false;
  21886. _this._worldMatrix = BABYLON.Matrix.Identity();
  21887. _this._postProcesses = new Array();
  21888. _this._transformMatrix = BABYLON.Matrix.Zero();
  21889. _this._activeMeshes = new BABYLON.SmartArray(256);
  21890. _this._globalPosition = BABYLON.Vector3.Zero();
  21891. _this._refreshFrustumPlanes = true;
  21892. _this.getScene().addCamera(_this);
  21893. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21894. _this.getScene().activeCamera = _this;
  21895. }
  21896. _this.position = position;
  21897. return _this;
  21898. }
  21899. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21900. get: function () {
  21901. return Camera._PERSPECTIVE_CAMERA;
  21902. },
  21903. enumerable: true,
  21904. configurable: true
  21905. });
  21906. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21907. get: function () {
  21908. return Camera._ORTHOGRAPHIC_CAMERA;
  21909. },
  21910. enumerable: true,
  21911. configurable: true
  21912. });
  21913. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21914. /**
  21915. * This is the default FOV mode for perspective cameras.
  21916. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21917. *
  21918. */
  21919. get: function () {
  21920. return Camera._FOVMODE_VERTICAL_FIXED;
  21921. },
  21922. enumerable: true,
  21923. configurable: true
  21924. });
  21925. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21926. /**
  21927. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21928. *
  21929. */
  21930. get: function () {
  21931. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21932. },
  21933. enumerable: true,
  21934. configurable: true
  21935. });
  21936. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21937. get: function () {
  21938. return Camera._RIG_MODE_NONE;
  21939. },
  21940. enumerable: true,
  21941. configurable: true
  21942. });
  21943. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21944. get: function () {
  21945. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21946. },
  21947. enumerable: true,
  21948. configurable: true
  21949. });
  21950. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21951. get: function () {
  21952. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21953. },
  21954. enumerable: true,
  21955. configurable: true
  21956. });
  21957. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21958. get: function () {
  21959. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21960. },
  21961. enumerable: true,
  21962. configurable: true
  21963. });
  21964. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21965. get: function () {
  21966. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21967. },
  21968. enumerable: true,
  21969. configurable: true
  21970. });
  21971. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21972. get: function () {
  21973. return Camera._RIG_MODE_VR;
  21974. },
  21975. enumerable: true,
  21976. configurable: true
  21977. });
  21978. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21979. get: function () {
  21980. return Camera._RIG_MODE_WEBVR;
  21981. },
  21982. enumerable: true,
  21983. configurable: true
  21984. });
  21985. /**
  21986. * Store current camera state (fov, position, etc..)
  21987. */
  21988. Camera.prototype.storeState = function () {
  21989. this._stateStored = true;
  21990. this._storedFov = this.fov;
  21991. return this;
  21992. };
  21993. /**
  21994. * Restores the camera state values if it has been stored. You must call storeState() first
  21995. */
  21996. Camera.prototype._restoreStateValues = function () {
  21997. if (!this._stateStored) {
  21998. return false;
  21999. }
  22000. this.fov = this._storedFov;
  22001. return true;
  22002. };
  22003. /**
  22004. * Restored camera state. You must call storeState() first
  22005. */
  22006. Camera.prototype.restoreState = function () {
  22007. if (this._restoreStateValues()) {
  22008. this.onRestoreStateObservable.notifyObservers(this);
  22009. return true;
  22010. }
  22011. return false;
  22012. };
  22013. Camera.prototype.getClassName = function () {
  22014. return "Camera";
  22015. };
  22016. /**
  22017. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22018. */
  22019. Camera.prototype.toString = function (fullDetails) {
  22020. var ret = "Name: " + this.name;
  22021. ret += ", type: " + this.getClassName();
  22022. if (this.animations) {
  22023. for (var i = 0; i < this.animations.length; i++) {
  22024. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22025. }
  22026. }
  22027. if (fullDetails) {
  22028. }
  22029. return ret;
  22030. };
  22031. Object.defineProperty(Camera.prototype, "globalPosition", {
  22032. get: function () {
  22033. return this._globalPosition;
  22034. },
  22035. enumerable: true,
  22036. configurable: true
  22037. });
  22038. Camera.prototype.getActiveMeshes = function () {
  22039. return this._activeMeshes;
  22040. };
  22041. Camera.prototype.isActiveMesh = function (mesh) {
  22042. return (this._activeMeshes.indexOf(mesh) !== -1);
  22043. };
  22044. /**
  22045. * Is this camera ready to be used/rendered
  22046. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22047. * @return true if the camera is ready
  22048. */
  22049. Camera.prototype.isReady = function (completeCheck) {
  22050. if (completeCheck === void 0) { completeCheck = false; }
  22051. if (completeCheck) {
  22052. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22053. var pp = _a[_i];
  22054. if (pp && !pp.isReady()) {
  22055. return false;
  22056. }
  22057. }
  22058. }
  22059. return _super.prototype.isReady.call(this, completeCheck);
  22060. };
  22061. //Cache
  22062. Camera.prototype._initCache = function () {
  22063. _super.prototype._initCache.call(this);
  22064. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22065. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22066. this._cache.mode = undefined;
  22067. this._cache.minZ = undefined;
  22068. this._cache.maxZ = undefined;
  22069. this._cache.fov = undefined;
  22070. this._cache.fovMode = undefined;
  22071. this._cache.aspectRatio = undefined;
  22072. this._cache.orthoLeft = undefined;
  22073. this._cache.orthoRight = undefined;
  22074. this._cache.orthoBottom = undefined;
  22075. this._cache.orthoTop = undefined;
  22076. this._cache.renderWidth = undefined;
  22077. this._cache.renderHeight = undefined;
  22078. };
  22079. Camera.prototype._updateCache = function (ignoreParentClass) {
  22080. if (!ignoreParentClass) {
  22081. _super.prototype._updateCache.call(this);
  22082. }
  22083. this._cache.position.copyFrom(this.position);
  22084. this._cache.upVector.copyFrom(this.upVector);
  22085. };
  22086. // Synchronized
  22087. Camera.prototype._isSynchronized = function () {
  22088. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22089. };
  22090. Camera.prototype._isSynchronizedViewMatrix = function () {
  22091. if (!_super.prototype._isSynchronized.call(this))
  22092. return false;
  22093. return this._cache.position.equals(this.position)
  22094. && this._cache.upVector.equals(this.upVector)
  22095. && this.isSynchronizedWithParent();
  22096. };
  22097. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22098. var check = this._cache.mode === this.mode
  22099. && this._cache.minZ === this.minZ
  22100. && this._cache.maxZ === this.maxZ;
  22101. if (!check) {
  22102. return false;
  22103. }
  22104. var engine = this.getEngine();
  22105. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22106. check = this._cache.fov === this.fov
  22107. && this._cache.fovMode === this.fovMode
  22108. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22109. }
  22110. else {
  22111. check = this._cache.orthoLeft === this.orthoLeft
  22112. && this._cache.orthoRight === this.orthoRight
  22113. && this._cache.orthoBottom === this.orthoBottom
  22114. && this._cache.orthoTop === this.orthoTop
  22115. && this._cache.renderWidth === engine.getRenderWidth()
  22116. && this._cache.renderHeight === engine.getRenderHeight();
  22117. }
  22118. return check;
  22119. };
  22120. // Controls
  22121. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22122. };
  22123. Camera.prototype.detachControl = function (element) {
  22124. };
  22125. Camera.prototype.update = function () {
  22126. this._checkInputs();
  22127. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22128. this._updateRigCameras();
  22129. }
  22130. };
  22131. Camera.prototype._checkInputs = function () {
  22132. this.onAfterCheckInputsObservable.notifyObservers(this);
  22133. };
  22134. Object.defineProperty(Camera.prototype, "rigCameras", {
  22135. get: function () {
  22136. return this._rigCameras;
  22137. },
  22138. enumerable: true,
  22139. configurable: true
  22140. });
  22141. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22142. get: function () {
  22143. return this._rigPostProcess;
  22144. },
  22145. enumerable: true,
  22146. configurable: true
  22147. });
  22148. /**
  22149. * Internal, gets the first post proces.
  22150. * @returns the first post process to be run on this camera.
  22151. */
  22152. Camera.prototype._getFirstPostProcess = function () {
  22153. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22154. if (this._postProcesses[ppIndex] !== null) {
  22155. return this._postProcesses[ppIndex];
  22156. }
  22157. }
  22158. return null;
  22159. };
  22160. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22161. // invalidate framebuffer
  22162. var firstPostProcess = this._getFirstPostProcess();
  22163. if (firstPostProcess) {
  22164. firstPostProcess.markTextureDirty();
  22165. }
  22166. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22167. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22168. var cam = this._rigCameras[i];
  22169. var rigPostProcess = cam._rigPostProcess;
  22170. // for VR rig, there does not have to be a post process
  22171. if (rigPostProcess) {
  22172. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22173. if (isPass) {
  22174. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22175. cam.isIntermediate = this._postProcesses.length === 0;
  22176. }
  22177. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22178. rigPostProcess.markTextureDirty();
  22179. }
  22180. else {
  22181. cam._postProcesses = this._postProcesses.slice(0);
  22182. }
  22183. }
  22184. };
  22185. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22186. if (insertAt === void 0) { insertAt = null; }
  22187. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22188. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22189. return 0;
  22190. }
  22191. if (insertAt == null || insertAt < 0) {
  22192. this._postProcesses.push(postProcess);
  22193. }
  22194. else if (this._postProcesses[insertAt] === null) {
  22195. this._postProcesses[insertAt] = postProcess;
  22196. }
  22197. else {
  22198. this._postProcesses.splice(insertAt, 0, postProcess);
  22199. }
  22200. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22201. return this._postProcesses.indexOf(postProcess);
  22202. };
  22203. Camera.prototype.detachPostProcess = function (postProcess) {
  22204. var idx = this._postProcesses.indexOf(postProcess);
  22205. if (idx !== -1) {
  22206. this._postProcesses[idx] = null;
  22207. }
  22208. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22209. };
  22210. Camera.prototype.getWorldMatrix = function () {
  22211. if (this._isSynchronizedViewMatrix()) {
  22212. return this._worldMatrix;
  22213. }
  22214. // Getting the the view matrix will also compute the world matrix.
  22215. this.getViewMatrix();
  22216. return this._worldMatrix;
  22217. };
  22218. Camera.prototype._getViewMatrix = function () {
  22219. return BABYLON.Matrix.Identity();
  22220. };
  22221. Camera.prototype.getViewMatrix = function (force) {
  22222. if (!force && this._isSynchronizedViewMatrix()) {
  22223. return this._computedViewMatrix;
  22224. }
  22225. this.updateCache();
  22226. this._computedViewMatrix = this._getViewMatrix();
  22227. this._currentRenderId = this.getScene().getRenderId();
  22228. this._childRenderId = this._currentRenderId;
  22229. this._refreshFrustumPlanes = true;
  22230. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22231. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22232. }
  22233. this.onViewMatrixChangedObservable.notifyObservers(this);
  22234. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22235. return this._computedViewMatrix;
  22236. };
  22237. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22238. this._doNotComputeProjectionMatrix = true;
  22239. if (projection !== undefined) {
  22240. this._projectionMatrix = projection;
  22241. }
  22242. };
  22243. ;
  22244. Camera.prototype.unfreezeProjectionMatrix = function () {
  22245. this._doNotComputeProjectionMatrix = false;
  22246. };
  22247. ;
  22248. Camera.prototype.getProjectionMatrix = function (force) {
  22249. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22250. return this._projectionMatrix;
  22251. }
  22252. // Cache
  22253. this._cache.mode = this.mode;
  22254. this._cache.minZ = this.minZ;
  22255. this._cache.maxZ = this.maxZ;
  22256. // Matrix
  22257. this._refreshFrustumPlanes = true;
  22258. var engine = this.getEngine();
  22259. var scene = this.getScene();
  22260. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22261. this._cache.fov = this.fov;
  22262. this._cache.fovMode = this.fovMode;
  22263. this._cache.aspectRatio = engine.getAspectRatio(this);
  22264. if (this.minZ <= 0) {
  22265. this.minZ = 0.1;
  22266. }
  22267. if (scene.useRightHandedSystem) {
  22268. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22269. }
  22270. else {
  22271. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22272. }
  22273. }
  22274. else {
  22275. var halfWidth = engine.getRenderWidth() / 2.0;
  22276. var halfHeight = engine.getRenderHeight() / 2.0;
  22277. if (scene.useRightHandedSystem) {
  22278. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22279. }
  22280. else {
  22281. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22282. }
  22283. this._cache.orthoLeft = this.orthoLeft;
  22284. this._cache.orthoRight = this.orthoRight;
  22285. this._cache.orthoBottom = this.orthoBottom;
  22286. this._cache.orthoTop = this.orthoTop;
  22287. this._cache.renderWidth = engine.getRenderWidth();
  22288. this._cache.renderHeight = engine.getRenderHeight();
  22289. }
  22290. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22291. return this._projectionMatrix;
  22292. };
  22293. Camera.prototype.getTranformationMatrix = function () {
  22294. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22295. return this._transformMatrix;
  22296. };
  22297. Camera.prototype.updateFrustumPlanes = function () {
  22298. if (!this._refreshFrustumPlanes) {
  22299. return;
  22300. }
  22301. this.getTranformationMatrix();
  22302. if (!this._frustumPlanes) {
  22303. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22304. }
  22305. else {
  22306. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22307. }
  22308. this._refreshFrustumPlanes = false;
  22309. };
  22310. Camera.prototype.isInFrustum = function (target) {
  22311. this.updateFrustumPlanes();
  22312. return target.isInFrustum(this._frustumPlanes);
  22313. };
  22314. Camera.prototype.isCompletelyInFrustum = function (target) {
  22315. this.updateFrustumPlanes();
  22316. return target.isCompletelyInFrustum(this._frustumPlanes);
  22317. };
  22318. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22319. if (length === void 0) { length = 100; }
  22320. if (!transform) {
  22321. transform = this.getWorldMatrix();
  22322. }
  22323. if (!origin) {
  22324. origin = this.position;
  22325. }
  22326. var forward = new BABYLON.Vector3(0, 0, 1);
  22327. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22328. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22329. return new BABYLON.Ray(origin, direction, length);
  22330. };
  22331. /**
  22332. * Releases resources associated with this node.
  22333. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22334. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22335. */
  22336. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22337. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22338. // Observables
  22339. this.onViewMatrixChangedObservable.clear();
  22340. this.onProjectionMatrixChangedObservable.clear();
  22341. this.onAfterCheckInputsObservable.clear();
  22342. this.onRestoreStateObservable.clear();
  22343. // Inputs
  22344. if (this.inputs) {
  22345. this.inputs.clear();
  22346. }
  22347. // Animations
  22348. this.getScene().stopAnimation(this);
  22349. // Remove from scene
  22350. this.getScene().removeCamera(this);
  22351. while (this._rigCameras.length > 0) {
  22352. var camera = this._rigCameras.pop();
  22353. if (camera) {
  22354. camera.dispose();
  22355. }
  22356. }
  22357. // Postprocesses
  22358. if (this._rigPostProcess) {
  22359. this._rigPostProcess.dispose(this);
  22360. this._rigPostProcess = null;
  22361. this._postProcesses = [];
  22362. }
  22363. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22364. this._rigPostProcess = null;
  22365. this._postProcesses = [];
  22366. }
  22367. else {
  22368. var i = this._postProcesses.length;
  22369. while (--i >= 0) {
  22370. var postProcess = this._postProcesses[i];
  22371. if (postProcess) {
  22372. postProcess.dispose(this);
  22373. }
  22374. }
  22375. }
  22376. // Render targets
  22377. var i = this.customRenderTargets.length;
  22378. while (--i >= 0) {
  22379. this.customRenderTargets[i].dispose();
  22380. }
  22381. this.customRenderTargets = [];
  22382. // Active Meshes
  22383. this._activeMeshes.dispose();
  22384. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22385. };
  22386. Object.defineProperty(Camera.prototype, "leftCamera", {
  22387. // ---- Camera rigs section ----
  22388. get: function () {
  22389. if (this._rigCameras.length < 1) {
  22390. return null;
  22391. }
  22392. return this._rigCameras[0];
  22393. },
  22394. enumerable: true,
  22395. configurable: true
  22396. });
  22397. Object.defineProperty(Camera.prototype, "rightCamera", {
  22398. get: function () {
  22399. if (this._rigCameras.length < 2) {
  22400. return null;
  22401. }
  22402. return this._rigCameras[1];
  22403. },
  22404. enumerable: true,
  22405. configurable: true
  22406. });
  22407. Camera.prototype.getLeftTarget = function () {
  22408. if (this._rigCameras.length < 1) {
  22409. return null;
  22410. }
  22411. return this._rigCameras[0].getTarget();
  22412. };
  22413. Camera.prototype.getRightTarget = function () {
  22414. if (this._rigCameras.length < 2) {
  22415. return null;
  22416. }
  22417. return this._rigCameras[1].getTarget();
  22418. };
  22419. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22420. if (this.cameraRigMode === mode) {
  22421. return;
  22422. }
  22423. while (this._rigCameras.length > 0) {
  22424. var camera = this._rigCameras.pop();
  22425. if (camera) {
  22426. camera.dispose();
  22427. }
  22428. }
  22429. this.cameraRigMode = mode;
  22430. this._cameraRigParams = {};
  22431. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22432. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22433. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22434. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22435. // create the rig cameras, unless none
  22436. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22437. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22438. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22439. if (leftCamera && rightCamera) {
  22440. this._rigCameras.push(leftCamera);
  22441. this._rigCameras.push(rightCamera);
  22442. }
  22443. }
  22444. switch (this.cameraRigMode) {
  22445. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22446. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22447. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22448. break;
  22449. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22450. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22451. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22452. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22453. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22454. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22455. break;
  22456. case Camera.RIG_MODE_VR:
  22457. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22458. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22459. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22460. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22461. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22462. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22463. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22464. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22465. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22466. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22467. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22468. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22469. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22470. if (metrics.compensateDistortion) {
  22471. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22472. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22473. }
  22474. break;
  22475. case Camera.RIG_MODE_WEBVR:
  22476. if (rigParams.vrDisplay) {
  22477. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22478. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22479. //Left eye
  22480. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22481. this._rigCameras[0].setCameraRigParameter("left", true);
  22482. //leaving this for future reference
  22483. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22484. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22485. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22486. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22487. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22488. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22489. this._rigCameras[0].parent = this;
  22490. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22491. //Right eye
  22492. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22493. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22494. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22495. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22496. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22497. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22498. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22499. this._rigCameras[1].parent = this;
  22500. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22501. if (Camera.UseAlternateWebVRRendering) {
  22502. this._rigCameras[1]._skipRendering = true;
  22503. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22504. }
  22505. }
  22506. break;
  22507. }
  22508. this._cascadePostProcessesToRigCams();
  22509. this.update();
  22510. };
  22511. Camera.prototype._getVRProjectionMatrix = function () {
  22512. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22513. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22514. return this._projectionMatrix;
  22515. };
  22516. Camera.prototype._updateCameraRotationMatrix = function () {
  22517. //Here for WebVR
  22518. };
  22519. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22520. //Here for WebVR
  22521. };
  22522. /**
  22523. * This function MUST be overwritten by the different WebVR cameras available.
  22524. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22525. */
  22526. Camera.prototype._getWebVRProjectionMatrix = function () {
  22527. return BABYLON.Matrix.Identity();
  22528. };
  22529. /**
  22530. * This function MUST be overwritten by the different WebVR cameras available.
  22531. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22532. */
  22533. Camera.prototype._getWebVRViewMatrix = function () {
  22534. return BABYLON.Matrix.Identity();
  22535. };
  22536. Camera.prototype.setCameraRigParameter = function (name, value) {
  22537. if (!this._cameraRigParams) {
  22538. this._cameraRigParams = {};
  22539. }
  22540. this._cameraRigParams[name] = value;
  22541. //provisionnally:
  22542. if (name === "interaxialDistance") {
  22543. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22544. }
  22545. };
  22546. /**
  22547. * needs to be overridden by children so sub has required properties to be copied
  22548. */
  22549. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22550. return null;
  22551. };
  22552. /**
  22553. * May need to be overridden by children
  22554. */
  22555. Camera.prototype._updateRigCameras = function () {
  22556. for (var i = 0; i < this._rigCameras.length; i++) {
  22557. this._rigCameras[i].minZ = this.minZ;
  22558. this._rigCameras[i].maxZ = this.maxZ;
  22559. this._rigCameras[i].fov = this.fov;
  22560. }
  22561. // only update viewport when ANAGLYPH
  22562. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22563. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22564. }
  22565. };
  22566. Camera.prototype._setupInputs = function () {
  22567. };
  22568. Camera.prototype.serialize = function () {
  22569. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22570. // Type
  22571. serializationObject.type = this.getClassName();
  22572. // Parent
  22573. if (this.parent) {
  22574. serializationObject.parentId = this.parent.id;
  22575. }
  22576. if (this.inputs) {
  22577. this.inputs.serialize(serializationObject);
  22578. }
  22579. // Animations
  22580. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22581. serializationObject.ranges = this.serializeAnimationRanges();
  22582. return serializationObject;
  22583. };
  22584. Camera.prototype.clone = function (name) {
  22585. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22586. };
  22587. Camera.prototype.getDirection = function (localAxis) {
  22588. var result = BABYLON.Vector3.Zero();
  22589. this.getDirectionToRef(localAxis, result);
  22590. return result;
  22591. };
  22592. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22593. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22594. };
  22595. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22596. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22597. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22598. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22599. interaxial_distance: interaxial_distance,
  22600. isStereoscopicSideBySide: isStereoscopicSideBySide
  22601. });
  22602. if (constructorFunc) {
  22603. return constructorFunc;
  22604. }
  22605. // Default to universal camera
  22606. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22607. };
  22608. Camera.prototype.computeWorldMatrix = function () {
  22609. return this.getWorldMatrix();
  22610. };
  22611. Camera.Parse = function (parsedCamera, scene) {
  22612. var type = parsedCamera.type;
  22613. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22614. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22615. // Parent
  22616. if (parsedCamera.parentId) {
  22617. camera._waitingParentId = parsedCamera.parentId;
  22618. }
  22619. //If camera has an input manager, let it parse inputs settings
  22620. if (camera.inputs) {
  22621. camera.inputs.parse(parsedCamera);
  22622. camera._setupInputs();
  22623. }
  22624. if (camera.setPosition) { // need to force position
  22625. camera.position.copyFromFloats(0, 0, 0);
  22626. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22627. }
  22628. // Target
  22629. if (parsedCamera.target) {
  22630. if (camera.setTarget) {
  22631. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22632. }
  22633. }
  22634. // Apply 3d rig, when found
  22635. if (parsedCamera.cameraRigMode) {
  22636. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22637. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22638. }
  22639. // Animations
  22640. if (parsedCamera.animations) {
  22641. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22642. var parsedAnimation = parsedCamera.animations[animationIndex];
  22643. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22644. }
  22645. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22646. }
  22647. if (parsedCamera.autoAnimate) {
  22648. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22649. }
  22650. return camera;
  22651. };
  22652. // Statics
  22653. Camera._PERSPECTIVE_CAMERA = 0;
  22654. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22655. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22656. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22657. Camera._RIG_MODE_NONE = 0;
  22658. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22659. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22660. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22661. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22662. Camera._RIG_MODE_VR = 20;
  22663. Camera._RIG_MODE_WEBVR = 21;
  22664. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22665. Camera.UseAlternateWebVRRendering = false;
  22666. __decorate([
  22667. BABYLON.serializeAsVector3()
  22668. ], Camera.prototype, "position", void 0);
  22669. __decorate([
  22670. BABYLON.serializeAsVector3()
  22671. ], Camera.prototype, "upVector", void 0);
  22672. __decorate([
  22673. BABYLON.serialize()
  22674. ], Camera.prototype, "orthoLeft", void 0);
  22675. __decorate([
  22676. BABYLON.serialize()
  22677. ], Camera.prototype, "orthoRight", void 0);
  22678. __decorate([
  22679. BABYLON.serialize()
  22680. ], Camera.prototype, "orthoBottom", void 0);
  22681. __decorate([
  22682. BABYLON.serialize()
  22683. ], Camera.prototype, "orthoTop", void 0);
  22684. __decorate([
  22685. BABYLON.serialize()
  22686. ], Camera.prototype, "fov", void 0);
  22687. __decorate([
  22688. BABYLON.serialize()
  22689. ], Camera.prototype, "minZ", void 0);
  22690. __decorate([
  22691. BABYLON.serialize()
  22692. ], Camera.prototype, "maxZ", void 0);
  22693. __decorate([
  22694. BABYLON.serialize()
  22695. ], Camera.prototype, "inertia", void 0);
  22696. __decorate([
  22697. BABYLON.serialize()
  22698. ], Camera.prototype, "mode", void 0);
  22699. __decorate([
  22700. BABYLON.serialize()
  22701. ], Camera.prototype, "layerMask", void 0);
  22702. __decorate([
  22703. BABYLON.serialize()
  22704. ], Camera.prototype, "fovMode", void 0);
  22705. __decorate([
  22706. BABYLON.serialize()
  22707. ], Camera.prototype, "cameraRigMode", void 0);
  22708. __decorate([
  22709. BABYLON.serialize()
  22710. ], Camera.prototype, "interaxialDistance", void 0);
  22711. __decorate([
  22712. BABYLON.serialize()
  22713. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22714. return Camera;
  22715. }(BABYLON.Node));
  22716. BABYLON.Camera = Camera;
  22717. })(BABYLON || (BABYLON = {}));
  22718. //# sourceMappingURL=babylon.camera.js.map
  22719. var BABYLON;
  22720. (function (BABYLON) {
  22721. var RenderingManager = /** @class */ (function () {
  22722. function RenderingManager(scene) {
  22723. /**
  22724. * Hidden
  22725. */
  22726. this._useSceneAutoClearSetup = false;
  22727. this._renderingGroups = new Array();
  22728. this._autoClearDepthStencil = {};
  22729. this._customOpaqueSortCompareFn = {};
  22730. this._customAlphaTestSortCompareFn = {};
  22731. this._customTransparentSortCompareFn = {};
  22732. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22733. this._scene = scene;
  22734. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22735. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22736. }
  22737. }
  22738. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22739. if (depth === void 0) { depth = true; }
  22740. if (stencil === void 0) { stencil = true; }
  22741. if (this._depthStencilBufferAlreadyCleaned) {
  22742. return;
  22743. }
  22744. this._scene.getEngine().clear(null, false, depth, stencil);
  22745. this._depthStencilBufferAlreadyCleaned = true;
  22746. };
  22747. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22748. // Update the observable context (not null as it only goes away on dispose)
  22749. var info = this._renderingGroupInfo;
  22750. info.scene = this._scene;
  22751. info.camera = this._scene.activeCamera;
  22752. // Dispatch sprites
  22753. if (renderSprites) {
  22754. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22755. var manager = this._scene.spriteManagers[index];
  22756. this.dispatchSprites(manager);
  22757. }
  22758. }
  22759. // Render
  22760. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22761. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22762. var renderingGroup = this._renderingGroups[index];
  22763. if (!renderingGroup)
  22764. continue;
  22765. var renderingGroupMask = Math.pow(2, index);
  22766. info.renderingGroupId = index;
  22767. // Before Observable
  22768. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22769. // Clear depth/stencil if needed
  22770. if (RenderingManager.AUTOCLEAR) {
  22771. var autoClear = this._useSceneAutoClearSetup ?
  22772. this._scene.getAutoClearDepthStencilSetup(index) :
  22773. this._autoClearDepthStencil[index];
  22774. if (autoClear && autoClear.autoClear) {
  22775. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22776. }
  22777. }
  22778. // Render
  22779. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22780. var step = _a[_i];
  22781. step.action(index);
  22782. }
  22783. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22784. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22785. var step = _c[_b];
  22786. step.action(index);
  22787. }
  22788. // After Observable
  22789. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22790. }
  22791. };
  22792. RenderingManager.prototype.reset = function () {
  22793. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22794. var renderingGroup = this._renderingGroups[index];
  22795. if (renderingGroup) {
  22796. renderingGroup.prepare();
  22797. }
  22798. }
  22799. };
  22800. RenderingManager.prototype.dispose = function () {
  22801. this.freeRenderingGroups();
  22802. this._renderingGroups.length = 0;
  22803. this._renderingGroupInfo = null;
  22804. };
  22805. /**
  22806. * Clear the info related to rendering groups preventing retention points during dispose.
  22807. */
  22808. RenderingManager.prototype.freeRenderingGroups = function () {
  22809. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22810. var renderingGroup = this._renderingGroups[index];
  22811. if (renderingGroup) {
  22812. renderingGroup.dispose();
  22813. }
  22814. }
  22815. };
  22816. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22817. if (this._renderingGroups[renderingGroupId] === undefined) {
  22818. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22819. }
  22820. };
  22821. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22822. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22823. this._prepareRenderingGroup(renderingGroupId);
  22824. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22825. };
  22826. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22827. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22828. this._prepareRenderingGroup(renderingGroupId);
  22829. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22830. };
  22831. /**
  22832. * @param subMesh The submesh to dispatch
  22833. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22834. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22835. */
  22836. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22837. if (mesh === undefined) {
  22838. mesh = subMesh.getMesh();
  22839. }
  22840. var renderingGroupId = mesh.renderingGroupId || 0;
  22841. this._prepareRenderingGroup(renderingGroupId);
  22842. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22843. };
  22844. /**
  22845. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22846. * This allowed control for front to back rendering or reversly depending of the special needs.
  22847. *
  22848. * @param renderingGroupId The rendering group id corresponding to its index
  22849. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22850. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22851. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22852. */
  22853. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22854. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22855. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22856. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22857. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22858. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22859. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22860. if (this._renderingGroups[renderingGroupId]) {
  22861. var group = this._renderingGroups[renderingGroupId];
  22862. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22863. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22864. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22865. }
  22866. };
  22867. /**
  22868. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22869. *
  22870. * @param renderingGroupId The rendering group id corresponding to its index
  22871. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22872. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22873. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22874. */
  22875. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22876. if (depth === void 0) { depth = true; }
  22877. if (stencil === void 0) { stencil = true; }
  22878. this._autoClearDepthStencil[renderingGroupId] = {
  22879. autoClear: autoClearDepthStencil,
  22880. depth: depth,
  22881. stencil: stencil
  22882. };
  22883. };
  22884. /**
  22885. * Gets the current auto clear configuration for one rendering group of the rendering
  22886. * manager.
  22887. * @param index the rendering group index to get the information for
  22888. * @returns The auto clear setup for the requested rendering group
  22889. */
  22890. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  22891. return this._autoClearDepthStencil[index];
  22892. };
  22893. /**
  22894. * The max id used for rendering groups (not included)
  22895. */
  22896. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22897. /**
  22898. * The min id used for rendering groups (included)
  22899. */
  22900. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22901. /**
  22902. * Used to globally prevent autoclearing scenes.
  22903. */
  22904. RenderingManager.AUTOCLEAR = true;
  22905. return RenderingManager;
  22906. }());
  22907. BABYLON.RenderingManager = RenderingManager;
  22908. })(BABYLON || (BABYLON = {}));
  22909. //# sourceMappingURL=babylon.renderingManager.js.map
  22910. var BABYLON;
  22911. (function (BABYLON) {
  22912. var RenderingGroup = /** @class */ (function () {
  22913. /**
  22914. * Creates a new rendering group.
  22915. * @param index The rendering group index
  22916. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22917. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22918. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22919. */
  22920. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22921. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22922. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22923. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22924. this.index = index;
  22925. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22926. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22927. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22928. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22929. this._particleSystems = new BABYLON.SmartArray(256);
  22930. this._spriteManagers = new BABYLON.SmartArray(256);
  22931. this._edgesRenderers = new BABYLON.SmartArray(16);
  22932. this._scene = scene;
  22933. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22934. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22935. this.transparentSortCompareFn = transparentSortCompareFn;
  22936. }
  22937. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22938. /**
  22939. * Set the opaque sort comparison function.
  22940. * If null the sub meshes will be render in the order they were created
  22941. */
  22942. set: function (value) {
  22943. this._opaqueSortCompareFn = value;
  22944. if (value) {
  22945. this._renderOpaque = this.renderOpaqueSorted;
  22946. }
  22947. else {
  22948. this._renderOpaque = RenderingGroup.renderUnsorted;
  22949. }
  22950. },
  22951. enumerable: true,
  22952. configurable: true
  22953. });
  22954. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22955. /**
  22956. * Set the alpha test sort comparison function.
  22957. * If null the sub meshes will be render in the order they were created
  22958. */
  22959. set: function (value) {
  22960. this._alphaTestSortCompareFn = value;
  22961. if (value) {
  22962. this._renderAlphaTest = this.renderAlphaTestSorted;
  22963. }
  22964. else {
  22965. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22966. }
  22967. },
  22968. enumerable: true,
  22969. configurable: true
  22970. });
  22971. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22972. /**
  22973. * Set the transparent sort comparison function.
  22974. * If null the sub meshes will be render in the order they were created
  22975. */
  22976. set: function (value) {
  22977. if (value) {
  22978. this._transparentSortCompareFn = value;
  22979. }
  22980. else {
  22981. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22982. }
  22983. this._renderTransparent = this.renderTransparentSorted;
  22984. },
  22985. enumerable: true,
  22986. configurable: true
  22987. });
  22988. /**
  22989. * Render all the sub meshes contained in the group.
  22990. * @param customRenderFunction Used to override the default render behaviour of the group.
  22991. * @returns true if rendered some submeshes.
  22992. */
  22993. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22994. if (customRenderFunction) {
  22995. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22996. return;
  22997. }
  22998. var engine = this._scene.getEngine();
  22999. // Depth only
  23000. if (this._depthOnlySubMeshes.length !== 0) {
  23001. engine.setColorWrite(false);
  23002. this._renderAlphaTest(this._depthOnlySubMeshes);
  23003. engine.setColorWrite(true);
  23004. }
  23005. // Opaque
  23006. if (this._opaqueSubMeshes.length !== 0) {
  23007. this._renderOpaque(this._opaqueSubMeshes);
  23008. }
  23009. // Alpha test
  23010. if (this._alphaTestSubMeshes.length !== 0) {
  23011. this._renderAlphaTest(this._alphaTestSubMeshes);
  23012. }
  23013. var stencilState = engine.getStencilBuffer();
  23014. engine.setStencilBuffer(false);
  23015. // Sprites
  23016. if (renderSprites) {
  23017. this._renderSprites();
  23018. }
  23019. // Particles
  23020. if (renderParticles) {
  23021. this._renderParticles(activeMeshes);
  23022. }
  23023. if (this.onBeforeTransparentRendering) {
  23024. this.onBeforeTransparentRendering();
  23025. }
  23026. // Transparent
  23027. if (this._transparentSubMeshes.length !== 0) {
  23028. this._renderTransparent(this._transparentSubMeshes);
  23029. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23030. }
  23031. // Set back stencil to false in case it changes before the edge renderer.
  23032. engine.setStencilBuffer(false);
  23033. // Edges
  23034. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23035. this._edgesRenderers.data[edgesRendererIndex].render();
  23036. }
  23037. // Restore Stencil state.
  23038. engine.setStencilBuffer(stencilState);
  23039. };
  23040. /**
  23041. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23042. * @param subMeshes The submeshes to render
  23043. */
  23044. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23045. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23046. };
  23047. /**
  23048. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23049. * @param subMeshes The submeshes to render
  23050. */
  23051. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23052. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23053. };
  23054. /**
  23055. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23056. * @param subMeshes The submeshes to render
  23057. */
  23058. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23059. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23060. };
  23061. /**
  23062. * Renders the submeshes in a specified order.
  23063. * @param subMeshes The submeshes to sort before render
  23064. * @param sortCompareFn The comparison function use to sort
  23065. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23066. * @param transparent Specifies to activate blending if true
  23067. */
  23068. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23069. var subIndex = 0;
  23070. var subMesh;
  23071. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23072. for (; subIndex < subMeshes.length; subIndex++) {
  23073. subMesh = subMeshes.data[subIndex];
  23074. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23075. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23076. }
  23077. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23078. if (sortCompareFn) {
  23079. sortedArray.sort(sortCompareFn);
  23080. }
  23081. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23082. subMesh = sortedArray[subIndex];
  23083. if (transparent) {
  23084. var material = subMesh.getMaterial();
  23085. if (material && material.needDepthPrePass) {
  23086. var engine = material.getScene().getEngine();
  23087. engine.setColorWrite(false);
  23088. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23089. subMesh.render(false);
  23090. engine.setColorWrite(true);
  23091. }
  23092. }
  23093. subMesh.render(transparent);
  23094. }
  23095. };
  23096. /**
  23097. * Renders the submeshes in the order they were dispatched (no sort applied).
  23098. * @param subMeshes The submeshes to render
  23099. */
  23100. RenderingGroup.renderUnsorted = function (subMeshes) {
  23101. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23102. var submesh = subMeshes.data[subIndex];
  23103. submesh.render(false);
  23104. }
  23105. };
  23106. /**
  23107. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23108. * are rendered back to front if in the same alpha index.
  23109. *
  23110. * @param a The first submesh
  23111. * @param b The second submesh
  23112. * @returns The result of the comparison
  23113. */
  23114. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23115. // Alpha index first
  23116. if (a._alphaIndex > b._alphaIndex) {
  23117. return 1;
  23118. }
  23119. if (a._alphaIndex < b._alphaIndex) {
  23120. return -1;
  23121. }
  23122. // Then distance to camera
  23123. return RenderingGroup.backToFrontSortCompare(a, b);
  23124. };
  23125. /**
  23126. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23127. * are rendered back to front.
  23128. *
  23129. * @param a The first submesh
  23130. * @param b The second submesh
  23131. * @returns The result of the comparison
  23132. */
  23133. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23134. // Then distance to camera
  23135. if (a._distanceToCamera < b._distanceToCamera) {
  23136. return 1;
  23137. }
  23138. if (a._distanceToCamera > b._distanceToCamera) {
  23139. return -1;
  23140. }
  23141. return 0;
  23142. };
  23143. /**
  23144. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23145. * are rendered front to back (prevent overdraw).
  23146. *
  23147. * @param a The first submesh
  23148. * @param b The second submesh
  23149. * @returns The result of the comparison
  23150. */
  23151. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23152. // Then distance to camera
  23153. if (a._distanceToCamera < b._distanceToCamera) {
  23154. return -1;
  23155. }
  23156. if (a._distanceToCamera > b._distanceToCamera) {
  23157. return 1;
  23158. }
  23159. return 0;
  23160. };
  23161. /**
  23162. * Resets the different lists of submeshes to prepare a new frame.
  23163. */
  23164. RenderingGroup.prototype.prepare = function () {
  23165. this._opaqueSubMeshes.reset();
  23166. this._transparentSubMeshes.reset();
  23167. this._alphaTestSubMeshes.reset();
  23168. this._depthOnlySubMeshes.reset();
  23169. this._particleSystems.reset();
  23170. this._spriteManagers.reset();
  23171. this._edgesRenderers.reset();
  23172. };
  23173. RenderingGroup.prototype.dispose = function () {
  23174. this._opaqueSubMeshes.dispose();
  23175. this._transparentSubMeshes.dispose();
  23176. this._alphaTestSubMeshes.dispose();
  23177. this._depthOnlySubMeshes.dispose();
  23178. this._particleSystems.dispose();
  23179. this._spriteManagers.dispose();
  23180. this._edgesRenderers.dispose();
  23181. };
  23182. /**
  23183. * Inserts the submesh in its correct queue depending on its material.
  23184. * @param subMesh The submesh to dispatch
  23185. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23186. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23187. */
  23188. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23189. // Get mesh and materials if not provided
  23190. if (mesh === undefined) {
  23191. mesh = subMesh.getMesh();
  23192. }
  23193. if (material === undefined) {
  23194. material = subMesh.getMaterial();
  23195. }
  23196. if (material === null || material === undefined) {
  23197. return;
  23198. }
  23199. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23200. this._transparentSubMeshes.push(subMesh);
  23201. }
  23202. else if (material.needAlphaTesting()) { // Alpha test
  23203. if (material.needDepthPrePass) {
  23204. this._depthOnlySubMeshes.push(subMesh);
  23205. }
  23206. this._alphaTestSubMeshes.push(subMesh);
  23207. }
  23208. else {
  23209. if (material.needDepthPrePass) {
  23210. this._depthOnlySubMeshes.push(subMesh);
  23211. }
  23212. this._opaqueSubMeshes.push(subMesh); // Opaque
  23213. }
  23214. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23215. this._edgesRenderers.push(mesh._edgesRenderer);
  23216. }
  23217. };
  23218. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23219. this._spriteManagers.push(spriteManager);
  23220. };
  23221. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23222. this._particleSystems.push(particleSystem);
  23223. };
  23224. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23225. if (this._particleSystems.length === 0) {
  23226. return;
  23227. }
  23228. // Particles
  23229. var activeCamera = this._scene.activeCamera;
  23230. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23231. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23232. var particleSystem = this._particleSystems.data[particleIndex];
  23233. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23234. continue;
  23235. }
  23236. var emitter = particleSystem.emitter;
  23237. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23238. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23239. }
  23240. }
  23241. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23242. };
  23243. RenderingGroup.prototype._renderSprites = function () {
  23244. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23245. return;
  23246. }
  23247. // Sprites
  23248. var activeCamera = this._scene.activeCamera;
  23249. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23250. for (var id = 0; id < this._spriteManagers.length; id++) {
  23251. var spriteManager = this._spriteManagers.data[id];
  23252. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23253. spriteManager.render();
  23254. }
  23255. }
  23256. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23257. };
  23258. return RenderingGroup;
  23259. }());
  23260. BABYLON.RenderingGroup = RenderingGroup;
  23261. })(BABYLON || (BABYLON = {}));
  23262. //# sourceMappingURL=babylon.renderingGroup.js.map
  23263. var BABYLON;
  23264. (function (BABYLON) {
  23265. /**
  23266. * Groups all the scene component constants in one place to ease maintenance.
  23267. * @hidden
  23268. */
  23269. var SceneComponentConstants = /** @class */ (function () {
  23270. function SceneComponentConstants() {
  23271. }
  23272. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23273. SceneComponentConstants.NAME_LAYER = "Layer";
  23274. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23275. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23276. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23277. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23278. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23279. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23280. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23281. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23282. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23283. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23284. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23285. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23286. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23287. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23288. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23289. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23290. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23291. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23292. return SceneComponentConstants;
  23293. }());
  23294. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23295. /**
  23296. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23297. * @hidden
  23298. */
  23299. var Stage = /** @class */ (function (_super) {
  23300. __extends(Stage, _super);
  23301. /**
  23302. * Hide ctor from the rest of the world.
  23303. * @param items The items to add.
  23304. */
  23305. function Stage(items) {
  23306. return _super.apply(this, items) || this;
  23307. }
  23308. /**
  23309. * Creates a new Stage.
  23310. * @returns A new instance of a Stage
  23311. */
  23312. Stage.Create = function () {
  23313. return Object.create(Stage.prototype);
  23314. };
  23315. /**
  23316. * Registers a step in an ordered way in the targeted stage.
  23317. * @param index Defines the position to register the step in
  23318. * @param component Defines the component attached to the step
  23319. * @param action Defines the action to launch during the step
  23320. */
  23321. Stage.prototype.registerStep = function (index, component, action) {
  23322. var i = 0;
  23323. var maxIndex = Number.MAX_VALUE;
  23324. for (; i < this.length && i < maxIndex; i++) {
  23325. var step = this[i];
  23326. maxIndex = step.index;
  23327. }
  23328. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23329. };
  23330. /**
  23331. * Clears all the steps from the stage.
  23332. */
  23333. Stage.prototype.clear = function () {
  23334. this.length = 0;
  23335. };
  23336. return Stage;
  23337. }(Array));
  23338. BABYLON.Stage = Stage;
  23339. })(BABYLON || (BABYLON = {}));
  23340. //# sourceMappingURL=babylon.sceneComponent.js.map
  23341. var BABYLON;
  23342. (function (BABYLON) {
  23343. /**
  23344. * Base class of the scene acting as a container for the different elements composing a scene.
  23345. * This class is dynamically extended by the different components of the scene increasing
  23346. * flexibility and reducing coupling
  23347. */
  23348. var AbstractScene = /** @class */ (function () {
  23349. function AbstractScene() {
  23350. /** All of the cameras added to this scene
  23351. * @see http://doc.babylonjs.com/babylon101/cameras
  23352. */
  23353. this.cameras = new Array();
  23354. /**
  23355. * All of the lights added to this scene
  23356. * @see http://doc.babylonjs.com/babylon101/lights
  23357. */
  23358. this.lights = new Array();
  23359. /**
  23360. * All of the (abstract) meshes added to this scene
  23361. */
  23362. this.meshes = new Array();
  23363. /**
  23364. * The list of skeletons added to the scene
  23365. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23366. */
  23367. this.skeletons = new Array();
  23368. /**
  23369. * All of the particle systems added to this scene
  23370. * @see http://doc.babylonjs.com/babylon101/particles
  23371. */
  23372. this.particleSystems = new Array();
  23373. /**
  23374. * Gets a list of Animations associated with the scene
  23375. */
  23376. this.animations = [];
  23377. /**
  23378. * All of the animation groups added to this scene
  23379. * @see http://doc.babylonjs.com/how_to/group
  23380. */
  23381. this.animationGroups = new Array();
  23382. /**
  23383. * All of the multi-materials added to this scene
  23384. * @see http://doc.babylonjs.com/how_to/multi_materials
  23385. */
  23386. this.multiMaterials = new Array();
  23387. /**
  23388. * All of the materials added to this scene
  23389. * @see http://doc.babylonjs.com/babylon101/materials
  23390. */
  23391. this.materials = new Array();
  23392. /**
  23393. * The list of morph target managers added to the scene
  23394. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23395. */
  23396. this.morphTargetManagers = new Array();
  23397. /**
  23398. * The list of geometries used in the scene.
  23399. */
  23400. this.geometries = new Array();
  23401. /**
  23402. * All of the tranform nodes added to this scene
  23403. * @see http://doc.babylonjs.com/how_to/transformnode
  23404. */
  23405. this.transformNodes = new Array();
  23406. /**
  23407. * ActionManagers available on the scene.
  23408. */
  23409. this.actionManagers = new Array();
  23410. /**
  23411. * Sounds to keep.
  23412. */
  23413. this.sounds = new Array();
  23414. /**
  23415. * Textures to keep.
  23416. */
  23417. this.textures = new Array();
  23418. }
  23419. /**
  23420. * Adds a parser in the list of available ones
  23421. * @param name Defines the name of the parser
  23422. * @param parser Defines the parser to add
  23423. */
  23424. AbstractScene.AddParser = function (name, parser) {
  23425. this._BabylonFileParsers[name] = parser;
  23426. };
  23427. /**
  23428. * Gets a general parser from the list of avaialble ones
  23429. * @param name Defines the name of the parser
  23430. * @returns the requested parser or null
  23431. */
  23432. AbstractScene.GetParser = function (name) {
  23433. if (this._BabylonFileParsers[name]) {
  23434. return this._BabylonFileParsers[name];
  23435. }
  23436. return null;
  23437. };
  23438. /**
  23439. * Adds n individual parser in the list of available ones
  23440. * @param name Defines the name of the parser
  23441. * @param parser Defines the parser to add
  23442. */
  23443. AbstractScene.AddIndividualParser = function (name, parser) {
  23444. this._IndividualBabylonFileParsers[name] = parser;
  23445. };
  23446. /**
  23447. * Gets an individual parser from the list of avaialble ones
  23448. * @param name Defines the name of the parser
  23449. * @returns the requested parser or null
  23450. */
  23451. AbstractScene.GetIndividualParser = function (name) {
  23452. if (this._IndividualBabylonFileParsers[name]) {
  23453. return this._IndividualBabylonFileParsers[name];
  23454. }
  23455. return null;
  23456. };
  23457. /**
  23458. * Parser json data and populate both a scene and its associated container object
  23459. * @param jsonData Defines the data to parse
  23460. * @param scene Defines the scene to parse the data for
  23461. * @param container Defines the container attached to the parsing sequence
  23462. * @param rootUrl Defines the root url of the data
  23463. */
  23464. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23465. for (var parserName in this._BabylonFileParsers) {
  23466. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23467. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23468. }
  23469. }
  23470. };
  23471. /**
  23472. * Stores the list of available parsers in the application.
  23473. */
  23474. AbstractScene._BabylonFileParsers = {};
  23475. /**
  23476. * Stores the list of available individual parsers in the application.
  23477. */
  23478. AbstractScene._IndividualBabylonFileParsers = {};
  23479. return AbstractScene;
  23480. }());
  23481. BABYLON.AbstractScene = AbstractScene;
  23482. })(BABYLON || (BABYLON = {}));
  23483. //# sourceMappingURL=babylon.abstractScene.js.map
  23484. var BABYLON;
  23485. (function (BABYLON) {
  23486. /** @hidden */
  23487. var ClickInfo = /** @class */ (function () {
  23488. function ClickInfo() {
  23489. this._singleClick = false;
  23490. this._doubleClick = false;
  23491. this._hasSwiped = false;
  23492. this._ignore = false;
  23493. }
  23494. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23495. get: function () {
  23496. return this._singleClick;
  23497. },
  23498. set: function (b) {
  23499. this._singleClick = b;
  23500. },
  23501. enumerable: true,
  23502. configurable: true
  23503. });
  23504. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23505. get: function () {
  23506. return this._doubleClick;
  23507. },
  23508. set: function (b) {
  23509. this._doubleClick = b;
  23510. },
  23511. enumerable: true,
  23512. configurable: true
  23513. });
  23514. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23515. get: function () {
  23516. return this._hasSwiped;
  23517. },
  23518. set: function (b) {
  23519. this._hasSwiped = b;
  23520. },
  23521. enumerable: true,
  23522. configurable: true
  23523. });
  23524. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23525. get: function () {
  23526. return this._ignore;
  23527. },
  23528. set: function (b) {
  23529. this._ignore = b;
  23530. },
  23531. enumerable: true,
  23532. configurable: true
  23533. });
  23534. return ClickInfo;
  23535. }());
  23536. /**
  23537. * This class is used by the onRenderingGroupObservable
  23538. */
  23539. var RenderingGroupInfo = /** @class */ (function () {
  23540. function RenderingGroupInfo() {
  23541. }
  23542. return RenderingGroupInfo;
  23543. }());
  23544. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23545. /**
  23546. * Represents a scene to be rendered by the engine.
  23547. * @see http://doc.babylonjs.com/features/scene
  23548. */
  23549. var Scene = /** @class */ (function (_super) {
  23550. __extends(Scene, _super);
  23551. /**
  23552. * Creates a new Scene
  23553. * @param engine defines the engine to use to render this scene
  23554. */
  23555. function Scene(engine) {
  23556. var _this = _super.call(this) || this;
  23557. // Members
  23558. /**
  23559. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23560. */
  23561. _this.autoClear = true;
  23562. /**
  23563. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23564. */
  23565. _this.autoClearDepthAndStencil = true;
  23566. /**
  23567. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23568. */
  23569. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23570. /**
  23571. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23572. */
  23573. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23574. _this._forceWireframe = false;
  23575. _this._forcePointsCloud = false;
  23576. /**
  23577. * Gets or sets a boolean indicating if animations are enabled
  23578. */
  23579. _this.animationsEnabled = true;
  23580. _this._animationPropertiesOverride = null;
  23581. /**
  23582. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23583. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23584. */
  23585. _this.useConstantAnimationDeltaTime = false;
  23586. /**
  23587. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23588. * Please note that it requires to run a ray cast through the scene on every frame
  23589. */
  23590. _this.constantlyUpdateMeshUnderPointer = false;
  23591. /**
  23592. * Defines the HTML cursor to use when hovering over interactive elements
  23593. */
  23594. _this.hoverCursor = "pointer";
  23595. /**
  23596. * Defines the HTML default cursor to use (empty by default)
  23597. */
  23598. _this.defaultCursor = "";
  23599. /**
  23600. * This is used to call preventDefault() on pointer down
  23601. * in order to block unwanted artifacts like system double clicks
  23602. */
  23603. _this.preventDefaultOnPointerDown = true;
  23604. // Metadata
  23605. /**
  23606. * Gets or sets user defined metadata
  23607. */
  23608. _this.metadata = null;
  23609. /**
  23610. * Use this array to add regular expressions used to disable offline support for specific urls
  23611. */
  23612. _this.disableOfflineSupportExceptionRules = new Array();
  23613. /**
  23614. * An event triggered when the scene is disposed.
  23615. */
  23616. _this.onDisposeObservable = new BABYLON.Observable();
  23617. _this._onDisposeObserver = null;
  23618. /**
  23619. * An event triggered before rendering the scene (right after animations and physics)
  23620. */
  23621. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23622. _this._onBeforeRenderObserver = null;
  23623. /**
  23624. * An event triggered after rendering the scene
  23625. */
  23626. _this.onAfterRenderObservable = new BABYLON.Observable();
  23627. _this._onAfterRenderObserver = null;
  23628. /**
  23629. * An event triggered before animating the scene
  23630. */
  23631. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23632. /**
  23633. * An event triggered after animations processing
  23634. */
  23635. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23636. /**
  23637. * An event triggered before draw calls are ready to be sent
  23638. */
  23639. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23640. /**
  23641. * An event triggered after draw calls have been sent
  23642. */
  23643. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23644. /**
  23645. * An event triggered when physic simulation is about to be run
  23646. */
  23647. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23648. /**
  23649. * An event triggered when physic simulation has been done
  23650. */
  23651. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23652. /**
  23653. * An event triggered when the scene is ready
  23654. */
  23655. _this.onReadyObservable = new BABYLON.Observable();
  23656. /**
  23657. * An event triggered before rendering a camera
  23658. */
  23659. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23660. _this._onBeforeCameraRenderObserver = null;
  23661. /**
  23662. * An event triggered after rendering a camera
  23663. */
  23664. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23665. _this._onAfterCameraRenderObserver = null;
  23666. /**
  23667. * An event triggered when active meshes evaluation is about to start
  23668. */
  23669. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23670. /**
  23671. * An event triggered when active meshes evaluation is done
  23672. */
  23673. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23674. /**
  23675. * An event triggered when particles rendering is about to start
  23676. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23677. */
  23678. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23679. /**
  23680. * An event triggered when particles rendering is done
  23681. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23682. */
  23683. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23684. /**
  23685. * An event triggered when sprites rendering is about to start
  23686. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23687. */
  23688. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23689. /**
  23690. * An event triggered when sprites rendering is done
  23691. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23692. */
  23693. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23694. /**
  23695. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23696. */
  23697. _this.onDataLoadedObservable = new BABYLON.Observable();
  23698. /**
  23699. * An event triggered when a camera is created
  23700. */
  23701. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered when a camera is removed
  23704. */
  23705. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23706. /**
  23707. * An event triggered when a light is created
  23708. */
  23709. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23710. /**
  23711. * An event triggered when a light is removed
  23712. */
  23713. _this.onLightRemovedObservable = new BABYLON.Observable();
  23714. /**
  23715. * An event triggered when a geometry is created
  23716. */
  23717. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23718. /**
  23719. * An event triggered when a geometry is removed
  23720. */
  23721. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23722. /**
  23723. * An event triggered when a transform node is created
  23724. */
  23725. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23726. /**
  23727. * An event triggered when a transform node is removed
  23728. */
  23729. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23730. /**
  23731. * An event triggered when a mesh is created
  23732. */
  23733. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23734. /**
  23735. * An event triggered when a mesh is removed
  23736. */
  23737. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23738. /**
  23739. * An event triggered when render targets are about to be rendered
  23740. * Can happen multiple times per frame.
  23741. */
  23742. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23743. /**
  23744. * An event triggered when render targets were rendered.
  23745. * Can happen multiple times per frame.
  23746. */
  23747. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23748. /**
  23749. * An event triggered before calculating deterministic simulation step
  23750. */
  23751. _this.onBeforeStepObservable = new BABYLON.Observable();
  23752. /**
  23753. * An event triggered after calculating deterministic simulation step
  23754. */
  23755. _this.onAfterStepObservable = new BABYLON.Observable();
  23756. /**
  23757. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  23758. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23759. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  23760. */
  23761. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23762. /**
  23763. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23764. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23765. * 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)
  23766. */
  23767. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23768. // Animations
  23769. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23770. /**
  23771. * 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).
  23772. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23773. */
  23774. _this.onPrePointerObservable = new BABYLON.Observable();
  23775. /**
  23776. * Observable event triggered each time an input event is received from the rendering canvas
  23777. */
  23778. _this.onPointerObservable = new BABYLON.Observable();
  23779. _this._meshPickProceed = false;
  23780. _this._currentPickResult = null;
  23781. _this._previousPickResult = null;
  23782. _this._totalPointersPressed = 0;
  23783. _this._doubleClickOccured = false;
  23784. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23785. _this.cameraToUseForPointers = null;
  23786. _this._pointerX = 0;
  23787. _this._pointerY = 0;
  23788. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23789. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23790. _this._startingPointerTime = 0;
  23791. _this._previousStartingPointerTime = 0;
  23792. _this._pointerCaptures = {};
  23793. // Deterministic lockstep
  23794. _this._timeAccumulator = 0;
  23795. _this._currentStepId = 0;
  23796. _this._currentInternalStep = 0;
  23797. // Keyboard
  23798. /**
  23799. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23800. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23801. */
  23802. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23803. /**
  23804. * Observable event triggered each time an keyboard event is received from the hosting window
  23805. */
  23806. _this.onKeyboardObservable = new BABYLON.Observable();
  23807. // Coordinates system
  23808. _this._useRightHandedSystem = false;
  23809. // Fog
  23810. _this._fogEnabled = true;
  23811. _this._fogMode = Scene.FOGMODE_NONE;
  23812. /**
  23813. * Gets or sets the fog color to use
  23814. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23815. */
  23816. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23817. /**
  23818. * Gets or sets the fog density to use
  23819. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23820. */
  23821. _this.fogDensity = 0.1;
  23822. /**
  23823. * Gets or sets the fog start distance to use
  23824. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23825. */
  23826. _this.fogStart = 0;
  23827. /**
  23828. * Gets or sets the fog end distance to use
  23829. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23830. */
  23831. _this.fogEnd = 1000.0;
  23832. // Lights
  23833. _this._shadowsEnabled = true;
  23834. _this._lightsEnabled = true;
  23835. /** All of the active cameras added to this scene. */
  23836. _this.activeCameras = new Array();
  23837. // Textures
  23838. _this._texturesEnabled = true;
  23839. // Particles
  23840. /**
  23841. * Gets or sets a boolean indicating if particles are enabled on this scene
  23842. */
  23843. _this.particlesEnabled = true;
  23844. // Sprites
  23845. /**
  23846. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23847. */
  23848. _this.spritesEnabled = true;
  23849. /**
  23850. * All of the sprite managers added to this scene
  23851. * @see http://doc.babylonjs.com/babylon101/sprites
  23852. */
  23853. _this.spriteManagers = new Array();
  23854. // Skeletons
  23855. _this._skeletonsEnabled = true;
  23856. // Lens flares
  23857. /**
  23858. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23859. */
  23860. _this.lensFlaresEnabled = true;
  23861. // Collisions
  23862. /**
  23863. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23864. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23865. */
  23866. _this.collisionsEnabled = true;
  23867. /**
  23868. * Defines the gravity applied to this scene (used only for collisions)
  23869. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23870. */
  23871. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23872. // Postprocesses
  23873. /**
  23874. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23875. */
  23876. _this.postProcessesEnabled = true;
  23877. /**
  23878. * The list of postprocesses added to the scene
  23879. */
  23880. _this.postProcesses = new Array();
  23881. // Customs render targets
  23882. /**
  23883. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23884. */
  23885. _this.renderTargetsEnabled = true;
  23886. /**
  23887. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23888. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23889. */
  23890. _this.dumpNextRenderTargets = false;
  23891. /**
  23892. * The list of user defined render targets added to the scene
  23893. */
  23894. _this.customRenderTargets = new Array();
  23895. /**
  23896. * Gets the list of meshes imported to the scene through SceneLoader
  23897. */
  23898. _this.importedMeshesFiles = new Array();
  23899. // Probes
  23900. /**
  23901. * Gets or sets a boolean indicating if probes are enabled on this scene
  23902. */
  23903. _this.probesEnabled = true;
  23904. /**
  23905. * The list of reflection probes added to the scene
  23906. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23907. */
  23908. _this.reflectionProbes = new Array();
  23909. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23910. // Procedural textures
  23911. /**
  23912. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23913. */
  23914. _this.proceduralTexturesEnabled = true;
  23915. /**
  23916. * The list of procedural textures added to the scene
  23917. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23918. */
  23919. _this.proceduralTextures = new Array();
  23920. /**
  23921. * The list of sound tracks added to the scene
  23922. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23923. */
  23924. _this.soundTracks = new Array();
  23925. _this._audioEnabled = true;
  23926. _this._headphone = false;
  23927. // Performance counters
  23928. _this._totalVertices = new BABYLON.PerfCounter();
  23929. /** @hidden */
  23930. _this._activeIndices = new BABYLON.PerfCounter();
  23931. /** @hidden */
  23932. _this._activeParticles = new BABYLON.PerfCounter();
  23933. /** @hidden */
  23934. _this._activeBones = new BABYLON.PerfCounter();
  23935. _this._animationTime = 0;
  23936. /**
  23937. * Gets or sets a general scale for animation speed
  23938. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23939. */
  23940. _this.animationTimeScale = 1;
  23941. _this._renderId = 0;
  23942. _this._executeWhenReadyTimeoutId = -1;
  23943. _this._intermediateRendering = false;
  23944. _this._viewUpdateFlag = -1;
  23945. _this._projectionUpdateFlag = -1;
  23946. _this._alternateViewUpdateFlag = -1;
  23947. _this._alternateProjectionUpdateFlag = -1;
  23948. /** @hidden */
  23949. _this._toBeDisposed = new BABYLON.SmartArray(256);
  23950. _this._activeRequests = new Array();
  23951. _this._pendingData = new Array();
  23952. _this._isDisposed = false;
  23953. /**
  23954. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23955. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23956. */
  23957. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  23958. _this._activeMeshes = new BABYLON.SmartArray(256);
  23959. _this._processedMaterials = new BABYLON.SmartArray(256);
  23960. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23961. /** @hidden */
  23962. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  23963. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23964. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23965. /** @hidden */
  23966. _this._activeAnimatables = new Array();
  23967. _this._transformMatrix = BABYLON.Matrix.Zero();
  23968. _this._useAlternateCameraConfiguration = false;
  23969. _this._alternateRendering = false;
  23970. /**
  23971. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23972. * This is useful if there are more lights that the maximum simulteanous authorized
  23973. */
  23974. _this.requireLightSorting = false;
  23975. _this._depthRenderer = {};
  23976. /**
  23977. * Backing store of defined scene components.
  23978. */
  23979. _this._components = [];
  23980. /**
  23981. * Backing store of defined scene components.
  23982. */
  23983. _this._serializableComponents = [];
  23984. /**
  23985. * List of components to register on the next registration step.
  23986. */
  23987. _this._transientComponents = [];
  23988. /**
  23989. * Defines the actions happening before camera updates.
  23990. */
  23991. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  23992. /**
  23993. * Defines the actions happening during the per mesh ready checks.
  23994. */
  23995. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  23996. /**
  23997. * Defines the actions happening before evaluate active mesh checks.
  23998. */
  23999. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24000. /**
  24001. * Defines the actions happening during the evaluate sub mesh checks.
  24002. */
  24003. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24004. /**
  24005. * Defines the actions happening during the active mesh stage.
  24006. */
  24007. _this._activeMeshStage = BABYLON.Stage.Create();
  24008. /**
  24009. * Defines the actions happening during the per camera render target step.
  24010. */
  24011. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24012. /**
  24013. * Defines the actions happening just before the active camera is drawing.
  24014. */
  24015. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24016. /**
  24017. * Defines the actions happening just before a rendering group is drawing.
  24018. */
  24019. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24020. /**
  24021. * Defines the actions happening just after a rendering group has been drawn.
  24022. */
  24023. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24024. /**
  24025. * Defines the actions happening just after the active camera has been drawn.
  24026. */
  24027. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24028. _this._activeMeshesFrozen = false;
  24029. /** @hidden */
  24030. _this._allowPostProcessClear = true;
  24031. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24032. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24033. _this._engine.scenes.push(_this);
  24034. _this._uid = null;
  24035. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24036. if (BABYLON.PostProcessManager) {
  24037. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24038. }
  24039. if (BABYLON.OutlineRenderer) {
  24040. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24041. }
  24042. if (BABYLON.Tools.IsWindowObjectExist()) {
  24043. _this.attachControl();
  24044. }
  24045. //simplification queue
  24046. if (BABYLON.SimplificationQueue) {
  24047. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24048. }
  24049. //collision coordinator initialization. For now legacy per default.
  24050. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24051. // Uniform Buffer
  24052. _this._createUbo();
  24053. // Default Image processing definition
  24054. if (BABYLON.ImageProcessingConfiguration) {
  24055. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24056. }
  24057. return _this;
  24058. }
  24059. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24060. /** The fog is deactivated */
  24061. get: function () {
  24062. return Scene._FOGMODE_NONE;
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24068. /** The fog density is following an exponential function */
  24069. get: function () {
  24070. return Scene._FOGMODE_EXP;
  24071. },
  24072. enumerable: true,
  24073. configurable: true
  24074. });
  24075. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24076. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24077. get: function () {
  24078. return Scene._FOGMODE_EXP2;
  24079. },
  24080. enumerable: true,
  24081. configurable: true
  24082. });
  24083. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24084. /** The fog density is following a linear function. */
  24085. get: function () {
  24086. return Scene._FOGMODE_LINEAR;
  24087. },
  24088. enumerable: true,
  24089. configurable: true
  24090. });
  24091. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24092. /**
  24093. * Texture used in all pbr material as the reflection texture.
  24094. * As in the majority of the scene they are the same (exception for multi room and so on),
  24095. * this is easier to reference from here than from all the materials.
  24096. */
  24097. get: function () {
  24098. return this._environmentTexture;
  24099. },
  24100. /**
  24101. * Texture used in all pbr material as the reflection texture.
  24102. * As in the majority of the scene they are the same (exception for multi room and so on),
  24103. * this is easier to set here than in all the materials.
  24104. */
  24105. set: function (value) {
  24106. if (this._environmentTexture === value) {
  24107. return;
  24108. }
  24109. this._environmentTexture = value;
  24110. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24111. },
  24112. enumerable: true,
  24113. configurable: true
  24114. });
  24115. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24116. /**
  24117. * Default image processing configuration used either in the rendering
  24118. * Forward main pass or through the imageProcessingPostProcess if present.
  24119. * As in the majority of the scene they are the same (exception for multi camera),
  24120. * this is easier to reference from here than from all the materials and post process.
  24121. *
  24122. * No setter as we it is a shared configuration, you can set the values instead.
  24123. */
  24124. get: function () {
  24125. return this._imageProcessingConfiguration;
  24126. },
  24127. enumerable: true,
  24128. configurable: true
  24129. });
  24130. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24131. get: function () {
  24132. return this._forceWireframe;
  24133. },
  24134. /**
  24135. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24136. */
  24137. set: function (value) {
  24138. if (this._forceWireframe === value) {
  24139. return;
  24140. }
  24141. this._forceWireframe = value;
  24142. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24143. },
  24144. enumerable: true,
  24145. configurable: true
  24146. });
  24147. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24148. get: function () {
  24149. return this._forcePointsCloud;
  24150. },
  24151. /**
  24152. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24153. */
  24154. set: function (value) {
  24155. if (this._forcePointsCloud === value) {
  24156. return;
  24157. }
  24158. this._forcePointsCloud = value;
  24159. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24160. },
  24161. enumerable: true,
  24162. configurable: true
  24163. });
  24164. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24165. /**
  24166. * Gets or sets the animation properties override
  24167. */
  24168. get: function () {
  24169. return this._animationPropertiesOverride;
  24170. },
  24171. set: function (value) {
  24172. this._animationPropertiesOverride = value;
  24173. },
  24174. enumerable: true,
  24175. configurable: true
  24176. });
  24177. Object.defineProperty(Scene.prototype, "onDispose", {
  24178. /** Sets a function to be executed when this scene is disposed. */
  24179. set: function (callback) {
  24180. if (this._onDisposeObserver) {
  24181. this.onDisposeObservable.remove(this._onDisposeObserver);
  24182. }
  24183. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24184. },
  24185. enumerable: true,
  24186. configurable: true
  24187. });
  24188. Object.defineProperty(Scene.prototype, "beforeRender", {
  24189. /** Sets a function to be executed before rendering this scene */
  24190. set: function (callback) {
  24191. if (this._onBeforeRenderObserver) {
  24192. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24193. }
  24194. if (callback) {
  24195. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24196. }
  24197. },
  24198. enumerable: true,
  24199. configurable: true
  24200. });
  24201. Object.defineProperty(Scene.prototype, "afterRender", {
  24202. /** Sets a function to be executed after rendering this scene */
  24203. set: function (callback) {
  24204. if (this._onAfterRenderObserver) {
  24205. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24206. }
  24207. if (callback) {
  24208. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24209. }
  24210. },
  24211. enumerable: true,
  24212. configurable: true
  24213. });
  24214. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24215. /** Sets a function to be executed before rendering a camera*/
  24216. set: function (callback) {
  24217. if (this._onBeforeCameraRenderObserver) {
  24218. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24219. }
  24220. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24226. /** Sets a function to be executed after rendering a camera*/
  24227. set: function (callback) {
  24228. if (this._onAfterCameraRenderObserver) {
  24229. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24230. }
  24231. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24232. },
  24233. enumerable: true,
  24234. configurable: true
  24235. });
  24236. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24237. /**
  24238. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24239. */
  24240. get: function () {
  24241. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24242. },
  24243. enumerable: true,
  24244. configurable: true
  24245. });
  24246. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24247. get: function () {
  24248. return this._useRightHandedSystem;
  24249. },
  24250. /**
  24251. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24252. */
  24253. set: function (value) {
  24254. if (this._useRightHandedSystem === value) {
  24255. return;
  24256. }
  24257. this._useRightHandedSystem = value;
  24258. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24259. },
  24260. enumerable: true,
  24261. configurable: true
  24262. });
  24263. /**
  24264. * Sets the step Id used by deterministic lock step
  24265. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24266. * @param newStepId defines the step Id
  24267. */
  24268. Scene.prototype.setStepId = function (newStepId) {
  24269. this._currentStepId = newStepId;
  24270. };
  24271. ;
  24272. /**
  24273. * Gets the step Id used by deterministic lock step
  24274. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24275. * @returns the step Id
  24276. */
  24277. Scene.prototype.getStepId = function () {
  24278. return this._currentStepId;
  24279. };
  24280. ;
  24281. /**
  24282. * Gets the internal step used by deterministic lock step
  24283. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24284. * @returns the internal step
  24285. */
  24286. Scene.prototype.getInternalStep = function () {
  24287. return this._currentInternalStep;
  24288. };
  24289. ;
  24290. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24291. get: function () {
  24292. return this._fogEnabled;
  24293. },
  24294. /**
  24295. * Gets or sets a boolean indicating if fog is enabled on this scene
  24296. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24297. */
  24298. set: function (value) {
  24299. if (this._fogEnabled === value) {
  24300. return;
  24301. }
  24302. this._fogEnabled = value;
  24303. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24304. },
  24305. enumerable: true,
  24306. configurable: true
  24307. });
  24308. Object.defineProperty(Scene.prototype, "fogMode", {
  24309. get: function () {
  24310. return this._fogMode;
  24311. },
  24312. /**
  24313. * Gets or sets the fog mode to use
  24314. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24315. */
  24316. set: function (value) {
  24317. if (this._fogMode === value) {
  24318. return;
  24319. }
  24320. this._fogMode = value;
  24321. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24322. },
  24323. enumerable: true,
  24324. configurable: true
  24325. });
  24326. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24327. get: function () {
  24328. return this._shadowsEnabled;
  24329. },
  24330. /**
  24331. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24332. */
  24333. set: function (value) {
  24334. if (this._shadowsEnabled === value) {
  24335. return;
  24336. }
  24337. this._shadowsEnabled = value;
  24338. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24344. get: function () {
  24345. return this._lightsEnabled;
  24346. },
  24347. /**
  24348. * Gets or sets a boolean indicating if lights are enabled on this scene
  24349. */
  24350. set: function (value) {
  24351. if (this._lightsEnabled === value) {
  24352. return;
  24353. }
  24354. this._lightsEnabled = value;
  24355. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24356. },
  24357. enumerable: true,
  24358. configurable: true
  24359. });
  24360. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24361. /** The default material used on meshes when no material is affected */
  24362. get: function () {
  24363. if (!this._defaultMaterial) {
  24364. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24365. }
  24366. return this._defaultMaterial;
  24367. },
  24368. /** The default material used on meshes when no material is affected */
  24369. set: function (value) {
  24370. this._defaultMaterial = value;
  24371. },
  24372. enumerable: true,
  24373. configurable: true
  24374. });
  24375. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24376. get: function () {
  24377. return this._texturesEnabled;
  24378. },
  24379. /**
  24380. * Gets or sets a boolean indicating if textures are enabled on this scene
  24381. */
  24382. set: function (value) {
  24383. if (this._texturesEnabled === value) {
  24384. return;
  24385. }
  24386. this._texturesEnabled = value;
  24387. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24388. },
  24389. enumerable: true,
  24390. configurable: true
  24391. });
  24392. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24393. get: function () {
  24394. return this._skeletonsEnabled;
  24395. },
  24396. /**
  24397. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24398. */
  24399. set: function (value) {
  24400. if (this._skeletonsEnabled === value) {
  24401. return;
  24402. }
  24403. this._skeletonsEnabled = value;
  24404. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24405. },
  24406. enumerable: true,
  24407. configurable: true
  24408. });
  24409. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24410. /**
  24411. * Gets the postprocess render pipeline manager
  24412. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24413. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24414. */
  24415. get: function () {
  24416. if (!this._postProcessRenderPipelineManager) {
  24417. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24418. }
  24419. return this._postProcessRenderPipelineManager;
  24420. },
  24421. enumerable: true,
  24422. configurable: true
  24423. });
  24424. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24425. /**
  24426. * Gets the main soundtrack associated with the scene
  24427. */
  24428. get: function () {
  24429. if (!this._mainSoundTrack) {
  24430. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24431. }
  24432. return this._mainSoundTrack;
  24433. },
  24434. enumerable: true,
  24435. configurable: true
  24436. });
  24437. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24438. /** @hidden */
  24439. get: function () {
  24440. return this._alternateRendering;
  24441. },
  24442. enumerable: true,
  24443. configurable: true
  24444. });
  24445. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24446. /**
  24447. * Gets the list of frustum planes (built from the active camera)
  24448. */
  24449. get: function () {
  24450. return this._frustumPlanes;
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24456. /**
  24457. * Gets the current geometry buffer associated to the scene.
  24458. */
  24459. get: function () {
  24460. return this._geometryBufferRenderer;
  24461. },
  24462. /**
  24463. * Sets the current geometry buffer for the scene.
  24464. */
  24465. set: function (geometryBufferRenderer) {
  24466. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24467. this._geometryBufferRenderer = geometryBufferRenderer;
  24468. }
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. /**
  24474. * Registers the transient components if needed.
  24475. */
  24476. Scene.prototype._registerTransientComponents = function () {
  24477. // Register components that have been associated lately to the scene.
  24478. if (this._transientComponents.length > 0) {
  24479. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24480. var component = _a[_i];
  24481. component.register();
  24482. }
  24483. this._transientComponents = [];
  24484. }
  24485. };
  24486. /**
  24487. * Add a component to the scene.
  24488. * Note that the ccomponent could be registered on th next frame if this is called after
  24489. * the register component stage.
  24490. * @param component Defines the component to add to the scene
  24491. */
  24492. Scene.prototype._addComponent = function (component) {
  24493. this._components.push(component);
  24494. this._transientComponents.push(component);
  24495. var serializableComponent = component;
  24496. if (serializableComponent.addFromContainer) {
  24497. this._serializableComponents.push(serializableComponent);
  24498. }
  24499. };
  24500. /**
  24501. * Gets a component from the scene.
  24502. * @param name defines the name of the component to retrieve
  24503. * @returns the component or null if not present
  24504. */
  24505. Scene.prototype._getComponent = function (name) {
  24506. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24507. var component = _a[_i];
  24508. if (component.name === name) {
  24509. return component;
  24510. }
  24511. }
  24512. return null;
  24513. };
  24514. Object.defineProperty(Scene.prototype, "debugLayer", {
  24515. /**
  24516. * Gets the debug layer (aka Inspector) associated with the scene
  24517. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24518. */
  24519. get: function () {
  24520. if (!this._debugLayer) {
  24521. this._debugLayer = new BABYLON.DebugLayer(this);
  24522. }
  24523. return this._debugLayer;
  24524. },
  24525. enumerable: true,
  24526. configurable: true
  24527. });
  24528. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24529. /**
  24530. * Gets a boolean indicating if collisions are processed on a web worker
  24531. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24532. */
  24533. get: function () {
  24534. return this._workerCollisions;
  24535. },
  24536. set: function (enabled) {
  24537. if (!BABYLON.CollisionCoordinatorLegacy) {
  24538. return;
  24539. }
  24540. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24541. this._workerCollisions = enabled;
  24542. if (this.collisionCoordinator) {
  24543. this.collisionCoordinator.destroy();
  24544. }
  24545. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24546. this.collisionCoordinator.init(this);
  24547. },
  24548. enumerable: true,
  24549. configurable: true
  24550. });
  24551. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24552. /**
  24553. * Gets the octree used to boost mesh selection (picking)
  24554. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24555. */
  24556. get: function () {
  24557. return this._selectionOctree;
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24563. /**
  24564. * Gets the mesh that is currently under the pointer
  24565. */
  24566. get: function () {
  24567. return this._pointerOverMesh;
  24568. },
  24569. enumerable: true,
  24570. configurable: true
  24571. });
  24572. Object.defineProperty(Scene.prototype, "pointerX", {
  24573. /**
  24574. * Gets the current on-screen X position of the pointer
  24575. */
  24576. get: function () {
  24577. return this._pointerX;
  24578. },
  24579. enumerable: true,
  24580. configurable: true
  24581. });
  24582. Object.defineProperty(Scene.prototype, "pointerY", {
  24583. /**
  24584. * Gets the current on-screen Y position of the pointer
  24585. */
  24586. get: function () {
  24587. return this._pointerY;
  24588. },
  24589. enumerable: true,
  24590. configurable: true
  24591. });
  24592. /**
  24593. * Gets the cached material (ie. the latest rendered one)
  24594. * @returns the cached material
  24595. */
  24596. Scene.prototype.getCachedMaterial = function () {
  24597. return this._cachedMaterial;
  24598. };
  24599. /**
  24600. * Gets the cached effect (ie. the latest rendered one)
  24601. * @returns the cached effect
  24602. */
  24603. Scene.prototype.getCachedEffect = function () {
  24604. return this._cachedEffect;
  24605. };
  24606. /**
  24607. * Gets the cached visibility state (ie. the latest rendered one)
  24608. * @returns the cached visibility state
  24609. */
  24610. Scene.prototype.getCachedVisibility = function () {
  24611. return this._cachedVisibility;
  24612. };
  24613. /**
  24614. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24615. * @param material defines the current material
  24616. * @param effect defines the current effect
  24617. * @param visibility defines the current visibility state
  24618. * @returns true if one parameter is not cached
  24619. */
  24620. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24621. if (visibility === void 0) { visibility = 1; }
  24622. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24623. };
  24624. /**
  24625. * Gets the outline renderer associated with the scene
  24626. * @returns a OutlineRenderer
  24627. */
  24628. Scene.prototype.getOutlineRenderer = function () {
  24629. return this._outlineRenderer;
  24630. };
  24631. /**
  24632. * Gets the engine associated with the scene
  24633. * @returns an Engine
  24634. */
  24635. Scene.prototype.getEngine = function () {
  24636. return this._engine;
  24637. };
  24638. /**
  24639. * Gets the total number of vertices rendered per frame
  24640. * @returns the total number of vertices rendered per frame
  24641. */
  24642. Scene.prototype.getTotalVertices = function () {
  24643. return this._totalVertices.current;
  24644. };
  24645. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24646. /**
  24647. * Gets the performance counter for total vertices
  24648. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24649. */
  24650. get: function () {
  24651. return this._totalVertices;
  24652. },
  24653. enumerable: true,
  24654. configurable: true
  24655. });
  24656. /**
  24657. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24658. * @returns the total number of active indices rendered per frame
  24659. */
  24660. Scene.prototype.getActiveIndices = function () {
  24661. return this._activeIndices.current;
  24662. };
  24663. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24664. /**
  24665. * Gets the performance counter for active indices
  24666. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24667. */
  24668. get: function () {
  24669. return this._activeIndices;
  24670. },
  24671. enumerable: true,
  24672. configurable: true
  24673. });
  24674. /**
  24675. * Gets the total number of active particles rendered per frame
  24676. * @returns the total number of active particles rendered per frame
  24677. */
  24678. Scene.prototype.getActiveParticles = function () {
  24679. return this._activeParticles.current;
  24680. };
  24681. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24682. /**
  24683. * Gets the performance counter for active particles
  24684. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24685. */
  24686. get: function () {
  24687. return this._activeParticles;
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. /**
  24693. * Gets the total number of active bones rendered per frame
  24694. * @returns the total number of active bones rendered per frame
  24695. */
  24696. Scene.prototype.getActiveBones = function () {
  24697. return this._activeBones.current;
  24698. };
  24699. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24700. /**
  24701. * Gets the performance counter for active bones
  24702. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24703. */
  24704. get: function () {
  24705. return this._activeBones;
  24706. },
  24707. enumerable: true,
  24708. configurable: true
  24709. });
  24710. /** @hidden */
  24711. Scene.prototype.getInterFramePerfCounter = function () {
  24712. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24713. return 0;
  24714. };
  24715. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24716. /** @hidden */
  24717. get: function () {
  24718. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24719. return null;
  24720. },
  24721. enumerable: true,
  24722. configurable: true
  24723. });
  24724. /** @hidden */
  24725. Scene.prototype.getLastFrameDuration = function () {
  24726. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24727. return 0;
  24728. };
  24729. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24730. /** @hidden */
  24731. get: function () {
  24732. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24733. return null;
  24734. },
  24735. enumerable: true,
  24736. configurable: true
  24737. });
  24738. /** @hidden */
  24739. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24740. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24741. return 0;
  24742. };
  24743. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24744. /** @hidden */
  24745. get: function () {
  24746. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24747. return null;
  24748. },
  24749. enumerable: true,
  24750. configurable: true
  24751. });
  24752. /**
  24753. * Gets the array of active meshes
  24754. * @returns an array of AbstractMesh
  24755. */
  24756. Scene.prototype.getActiveMeshes = function () {
  24757. return this._activeMeshes;
  24758. };
  24759. /** @hidden */
  24760. Scene.prototype.getRenderTargetsDuration = function () {
  24761. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24762. return 0;
  24763. };
  24764. /** @hidden */
  24765. Scene.prototype.getRenderDuration = function () {
  24766. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24767. return 0;
  24768. };
  24769. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24770. /** @hidden */
  24771. get: function () {
  24772. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24773. return null;
  24774. },
  24775. enumerable: true,
  24776. configurable: true
  24777. });
  24778. /** @hidden */
  24779. Scene.prototype.getParticlesDuration = function () {
  24780. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24781. return 0;
  24782. };
  24783. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24784. /** @hidden */
  24785. get: function () {
  24786. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24787. return null;
  24788. },
  24789. enumerable: true,
  24790. configurable: true
  24791. });
  24792. /** @hidden */
  24793. Scene.prototype.getSpritesDuration = function () {
  24794. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24795. return 0;
  24796. };
  24797. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24798. /** @hidden */
  24799. get: function () {
  24800. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24801. return null;
  24802. },
  24803. enumerable: true,
  24804. configurable: true
  24805. });
  24806. /**
  24807. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24808. * @returns a number
  24809. */
  24810. Scene.prototype.getAnimationRatio = function () {
  24811. return this._animationRatio !== undefined ? this._animationRatio : 1;
  24812. };
  24813. /**
  24814. * Gets an unique Id for the current frame
  24815. * @returns a number
  24816. */
  24817. Scene.prototype.getRenderId = function () {
  24818. return this._renderId;
  24819. };
  24820. /** Call this function if you want to manually increment the render Id*/
  24821. Scene.prototype.incrementRenderId = function () {
  24822. this._renderId++;
  24823. };
  24824. Scene.prototype._updatePointerPosition = function (evt) {
  24825. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24826. if (!canvasRect) {
  24827. return;
  24828. }
  24829. this._pointerX = evt.clientX - canvasRect.left;
  24830. this._pointerY = evt.clientY - canvasRect.top;
  24831. this._unTranslatedPointerX = this._pointerX;
  24832. this._unTranslatedPointerY = this._pointerY;
  24833. };
  24834. Scene.prototype._createUbo = function () {
  24835. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24836. this._sceneUbo.addUniform("viewProjection", 16);
  24837. this._sceneUbo.addUniform("view", 16);
  24838. };
  24839. Scene.prototype._createAlternateUbo = function () {
  24840. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24841. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24842. this._alternateSceneUbo.addUniform("view", 16);
  24843. };
  24844. // Pointers handling
  24845. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24846. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24847. if (result) {
  24848. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24849. }
  24850. return result;
  24851. };
  24852. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24853. if (pointerInfo.pickInfo) {
  24854. if (!pointerInfo.pickInfo.ray) {
  24855. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24856. }
  24857. }
  24858. };
  24859. /**
  24860. * Use this method to simulate a pointer move on a mesh
  24861. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24862. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24863. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24864. * @returns the current scene
  24865. */
  24866. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24867. var evt = new PointerEvent("pointermove", pointerEventInit);
  24868. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24869. return this;
  24870. }
  24871. return this._processPointerMove(pickResult, evt);
  24872. };
  24873. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24874. var canvas = this._engine.getRenderingCanvas();
  24875. if (!canvas) {
  24876. return this;
  24877. }
  24878. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24879. this.setPointerOverSprite(null);
  24880. this.setPointerOverMesh(pickResult.pickedMesh);
  24881. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24882. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24883. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24884. }
  24885. else {
  24886. canvas.style.cursor = this.hoverCursor;
  24887. }
  24888. }
  24889. else {
  24890. canvas.style.cursor = this.defaultCursor;
  24891. }
  24892. }
  24893. else {
  24894. this.setPointerOverMesh(null);
  24895. // Sprites
  24896. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24897. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24898. this.setPointerOverSprite(pickResult.pickedSprite);
  24899. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24900. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24901. }
  24902. else {
  24903. canvas.style.cursor = this.hoverCursor;
  24904. }
  24905. }
  24906. else {
  24907. this.setPointerOverSprite(null);
  24908. // Restore pointer
  24909. canvas.style.cursor = this.defaultCursor;
  24910. }
  24911. }
  24912. if (pickResult) {
  24913. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24914. if (this.onPointerMove) {
  24915. this.onPointerMove(evt, pickResult, type);
  24916. }
  24917. if (this.onPointerObservable.hasObservers()) {
  24918. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24919. this._setRayOnPointerInfo(pi);
  24920. this.onPointerObservable.notifyObservers(pi, type);
  24921. }
  24922. }
  24923. return this;
  24924. };
  24925. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  24926. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  24927. if (pickResult) {
  24928. pi.ray = pickResult.ray;
  24929. }
  24930. this.onPrePointerObservable.notifyObservers(pi, type);
  24931. if (pi.skipOnPointerObservable) {
  24932. return true;
  24933. }
  24934. else {
  24935. return false;
  24936. }
  24937. };
  24938. /**
  24939. * Use this method to simulate a pointer down on a mesh
  24940. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24941. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24942. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24943. * @returns the current scene
  24944. */
  24945. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24946. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24947. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  24948. return this;
  24949. }
  24950. return this._processPointerDown(pickResult, evt);
  24951. };
  24952. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24953. var _this = this;
  24954. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24955. this._pickedDownMesh = pickResult.pickedMesh;
  24956. var actionManager = pickResult.pickedMesh.actionManager;
  24957. if (actionManager) {
  24958. if (actionManager.hasPickTriggers) {
  24959. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24960. switch (evt.button) {
  24961. case 0:
  24962. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24963. break;
  24964. case 1:
  24965. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24966. break;
  24967. case 2:
  24968. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24969. break;
  24970. }
  24971. }
  24972. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24973. window.setTimeout(function () {
  24974. 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);
  24975. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24976. if (_this._totalPointersPressed !== 0 &&
  24977. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24978. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24979. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24980. _this._startingPointerTime = 0;
  24981. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24982. }
  24983. }
  24984. }, Scene.LongPressDelay);
  24985. }
  24986. }
  24987. }
  24988. if (pickResult) {
  24989. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24990. if (this.onPointerDown) {
  24991. this.onPointerDown(evt, pickResult, type);
  24992. }
  24993. if (this.onPointerObservable.hasObservers()) {
  24994. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24995. this._setRayOnPointerInfo(pi);
  24996. this.onPointerObservable.notifyObservers(pi, type);
  24997. }
  24998. }
  24999. return this;
  25000. };
  25001. /**
  25002. * Use this method to simulate a pointer up on a mesh
  25003. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25004. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25005. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25006. * @returns the current scene
  25007. */
  25008. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25009. var evt = new PointerEvent("pointerup", pointerEventInit);
  25010. var clickInfo = new ClickInfo();
  25011. clickInfo.singleClick = true;
  25012. clickInfo.ignore = true;
  25013. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25014. return this;
  25015. }
  25016. return this._processPointerUp(pickResult, evt, clickInfo);
  25017. };
  25018. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25019. if (pickResult && pickResult && pickResult.pickedMesh) {
  25020. this._pickedUpMesh = pickResult.pickedMesh;
  25021. if (this._pickedDownMesh === this._pickedUpMesh) {
  25022. if (this.onPointerPick) {
  25023. this.onPointerPick(evt, pickResult);
  25024. }
  25025. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25026. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25027. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25028. this._setRayOnPointerInfo(pi);
  25029. this.onPointerObservable.notifyObservers(pi, type_1);
  25030. }
  25031. }
  25032. if (pickResult.pickedMesh.actionManager) {
  25033. if (clickInfo.ignore) {
  25034. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25035. }
  25036. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25037. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25038. }
  25039. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25040. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25041. }
  25042. }
  25043. }
  25044. if (this._pickedDownMesh &&
  25045. this._pickedDownMesh.actionManager &&
  25046. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25047. this._pickedDownMesh !== this._pickedUpMesh) {
  25048. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25049. }
  25050. var type = BABYLON.PointerEventTypes.POINTERUP;
  25051. if (this.onPointerObservable.hasObservers()) {
  25052. if (!clickInfo.ignore) {
  25053. if (!clickInfo.hasSwiped) {
  25054. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25055. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25056. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25057. this._setRayOnPointerInfo(pi);
  25058. this.onPointerObservable.notifyObservers(pi, type_2);
  25059. }
  25060. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25061. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25062. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25063. this._setRayOnPointerInfo(pi);
  25064. this.onPointerObservable.notifyObservers(pi, type_3);
  25065. }
  25066. }
  25067. }
  25068. else {
  25069. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25070. this._setRayOnPointerInfo(pi);
  25071. this.onPointerObservable.notifyObservers(pi, type);
  25072. }
  25073. }
  25074. if (this.onPointerUp) {
  25075. this.onPointerUp(evt, pickResult, type);
  25076. }
  25077. return this;
  25078. };
  25079. /**
  25080. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25081. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25082. * @returns true if the pointer was captured
  25083. */
  25084. Scene.prototype.isPointerCaptured = function (pointerId) {
  25085. if (pointerId === void 0) { pointerId = 0; }
  25086. return this._pointerCaptures[pointerId];
  25087. };
  25088. /**
  25089. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25090. * @param attachUp defines if you want to attach events to pointerup
  25091. * @param attachDown defines if you want to attach events to pointerdown
  25092. * @param attachMove defines if you want to attach events to pointermove
  25093. */
  25094. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25095. var _this = this;
  25096. if (attachUp === void 0) { attachUp = true; }
  25097. if (attachDown === void 0) { attachDown = true; }
  25098. if (attachMove === void 0) { attachMove = true; }
  25099. this._initActionManager = function (act, clickInfo) {
  25100. if (!_this._meshPickProceed) {
  25101. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25102. _this._currentPickResult = pickResult;
  25103. if (pickResult) {
  25104. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25105. }
  25106. _this._meshPickProceed = true;
  25107. }
  25108. return act;
  25109. };
  25110. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25111. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25112. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25113. btn !== _this._previousButtonPressed) {
  25114. _this._doubleClickOccured = false;
  25115. clickInfo.singleClick = true;
  25116. clickInfo.ignore = false;
  25117. cb(clickInfo, _this._currentPickResult);
  25118. }
  25119. };
  25120. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25121. var clickInfo = new ClickInfo();
  25122. _this._currentPickResult = null;
  25123. var act = null;
  25124. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25125. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25126. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25127. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25128. act = _this._initActionManager(act, clickInfo);
  25129. if (act)
  25130. checkPicking = act.hasPickTriggers;
  25131. }
  25132. if (checkPicking) {
  25133. var btn = evt.button;
  25134. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25135. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25136. if (!clickInfo.hasSwiped) {
  25137. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25138. if (!checkSingleClickImmediately) {
  25139. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25140. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25141. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25142. act = _this._initActionManager(act, clickInfo);
  25143. if (act)
  25144. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25145. }
  25146. }
  25147. if (checkSingleClickImmediately) {
  25148. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25149. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25150. btn !== _this._previousButtonPressed) {
  25151. clickInfo.singleClick = true;
  25152. cb(clickInfo, _this._currentPickResult);
  25153. }
  25154. }
  25155. // at least one double click is required to be check and exclusive double click is enabled
  25156. else {
  25157. // wait that no double click has been raised during the double click delay
  25158. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25159. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25160. }
  25161. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25162. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25163. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25164. act = _this._initActionManager(act, clickInfo);
  25165. if (act)
  25166. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25167. }
  25168. if (checkDoubleClick) {
  25169. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25170. if (btn === _this._previousButtonPressed &&
  25171. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25172. !_this._doubleClickOccured) {
  25173. // pointer has not moved for 2 clicks, it's a double click
  25174. if (!clickInfo.hasSwiped &&
  25175. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25176. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25177. _this._previousStartingPointerTime = 0;
  25178. _this._doubleClickOccured = true;
  25179. clickInfo.doubleClick = true;
  25180. clickInfo.ignore = false;
  25181. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25182. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25183. }
  25184. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25185. cb(clickInfo, _this._currentPickResult);
  25186. }
  25187. // if the two successive clicks are too far, it's just two simple clicks
  25188. else {
  25189. _this._doubleClickOccured = false;
  25190. _this._previousStartingPointerTime = _this._startingPointerTime;
  25191. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25192. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25193. _this._previousButtonPressed = btn;
  25194. if (Scene.ExclusiveDoubleClickMode) {
  25195. if (_this._previousDelayedSimpleClickTimeout) {
  25196. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25197. }
  25198. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25199. cb(clickInfo, _this._previousPickResult);
  25200. }
  25201. else {
  25202. cb(clickInfo, _this._currentPickResult);
  25203. }
  25204. }
  25205. }
  25206. // just the first click of the double has been raised
  25207. else {
  25208. _this._doubleClickOccured = false;
  25209. _this._previousStartingPointerTime = _this._startingPointerTime;
  25210. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25211. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25212. _this._previousButtonPressed = btn;
  25213. }
  25214. }
  25215. }
  25216. }
  25217. clickInfo.ignore = true;
  25218. cb(clickInfo, _this._currentPickResult);
  25219. };
  25220. this._spritePredicate = function (sprite) {
  25221. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25222. };
  25223. this._onPointerMove = function (evt) {
  25224. _this._updatePointerPosition(evt);
  25225. // PreObservable support
  25226. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25227. return;
  25228. }
  25229. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25230. return;
  25231. }
  25232. if (!_this.pointerMovePredicate) {
  25233. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25234. }
  25235. // Meshes
  25236. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25237. _this._processPointerMove(pickResult, evt);
  25238. };
  25239. this._onPointerDown = function (evt) {
  25240. _this._totalPointersPressed++;
  25241. _this._pickedDownMesh = null;
  25242. _this._meshPickProceed = false;
  25243. _this._updatePointerPosition(evt);
  25244. if (_this.preventDefaultOnPointerDown && canvas) {
  25245. evt.preventDefault();
  25246. canvas.focus();
  25247. }
  25248. // PreObservable support
  25249. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25250. return;
  25251. }
  25252. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25253. return;
  25254. }
  25255. _this._pointerCaptures[evt.pointerId] = true;
  25256. _this._startingPointerPosition.x = _this._pointerX;
  25257. _this._startingPointerPosition.y = _this._pointerY;
  25258. _this._startingPointerTime = Date.now();
  25259. if (!_this.pointerDownPredicate) {
  25260. _this.pointerDownPredicate = function (mesh) {
  25261. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25262. };
  25263. }
  25264. // Meshes
  25265. _this._pickedDownMesh = null;
  25266. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25267. _this._processPointerDown(pickResult, evt);
  25268. // Sprites
  25269. _this._pickedDownSprite = null;
  25270. if (_this.spriteManagers.length > 0) {
  25271. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25272. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25273. if (pickResult.pickedSprite.actionManager) {
  25274. _this._pickedDownSprite = pickResult.pickedSprite;
  25275. switch (evt.button) {
  25276. case 0:
  25277. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25278. break;
  25279. case 1:
  25280. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25281. break;
  25282. case 2:
  25283. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25284. break;
  25285. }
  25286. if (pickResult.pickedSprite.actionManager) {
  25287. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25288. }
  25289. }
  25290. }
  25291. }
  25292. };
  25293. this._onPointerUp = function (evt) {
  25294. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25295. return; // So we need to test it the pointer down was pressed before.
  25296. }
  25297. _this._totalPointersPressed--;
  25298. _this._pickedUpMesh = null;
  25299. _this._meshPickProceed = false;
  25300. _this._updatePointerPosition(evt);
  25301. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25302. // PreObservable support
  25303. if (_this.onPrePointerObservable.hasObservers()) {
  25304. if (!clickInfo.ignore) {
  25305. if (!clickInfo.hasSwiped) {
  25306. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25307. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25308. return;
  25309. }
  25310. }
  25311. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25312. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25313. return;
  25314. }
  25315. }
  25316. }
  25317. }
  25318. else {
  25319. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25320. return;
  25321. }
  25322. }
  25323. }
  25324. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25325. return;
  25326. }
  25327. _this._pointerCaptures[evt.pointerId] = false;
  25328. if (!_this.pointerUpPredicate) {
  25329. _this.pointerUpPredicate = function (mesh) {
  25330. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25331. };
  25332. }
  25333. // Meshes
  25334. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25335. _this._initActionManager(null, clickInfo);
  25336. }
  25337. if (!pickResult) {
  25338. pickResult = _this._currentPickResult;
  25339. }
  25340. _this._processPointerUp(pickResult, evt, clickInfo);
  25341. // Sprites
  25342. if (!clickInfo.ignore) {
  25343. if (_this.spriteManagers.length > 0) {
  25344. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25345. if (spritePickResult) {
  25346. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25347. if (spritePickResult.pickedSprite.actionManager) {
  25348. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25349. if (spritePickResult.pickedSprite.actionManager) {
  25350. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25351. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25352. }
  25353. }
  25354. }
  25355. }
  25356. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25357. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25358. }
  25359. }
  25360. }
  25361. }
  25362. _this._previousPickResult = _this._currentPickResult;
  25363. });
  25364. };
  25365. this._onKeyDown = function (evt) {
  25366. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25367. if (_this.onPreKeyboardObservable.hasObservers()) {
  25368. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25369. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25370. if (pi.skipOnPointerObservable) {
  25371. return;
  25372. }
  25373. }
  25374. if (_this.onKeyboardObservable.hasObservers()) {
  25375. var pi = new BABYLON.KeyboardInfo(type, evt);
  25376. _this.onKeyboardObservable.notifyObservers(pi, type);
  25377. }
  25378. if (_this.actionManager) {
  25379. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25380. }
  25381. };
  25382. this._onKeyUp = function (evt) {
  25383. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25384. if (_this.onPreKeyboardObservable.hasObservers()) {
  25385. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25386. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25387. if (pi.skipOnPointerObservable) {
  25388. return;
  25389. }
  25390. }
  25391. if (_this.onKeyboardObservable.hasObservers()) {
  25392. var pi = new BABYLON.KeyboardInfo(type, evt);
  25393. _this.onKeyboardObservable.notifyObservers(pi, type);
  25394. }
  25395. if (_this.actionManager) {
  25396. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25397. }
  25398. };
  25399. var engine = this.getEngine();
  25400. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25401. if (!canvas) {
  25402. return;
  25403. }
  25404. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25405. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25406. });
  25407. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25408. if (!canvas) {
  25409. return;
  25410. }
  25411. canvas.removeEventListener("keydown", _this._onKeyDown);
  25412. canvas.removeEventListener("keyup", _this._onKeyUp);
  25413. });
  25414. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25415. var canvas = this._engine.getRenderingCanvas();
  25416. if (!canvas) {
  25417. return;
  25418. }
  25419. if (attachMove) {
  25420. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25421. // Wheel
  25422. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25423. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25424. }
  25425. if (attachDown) {
  25426. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25427. }
  25428. if (attachUp) {
  25429. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25430. }
  25431. canvas.tabIndex = 1;
  25432. };
  25433. /** Detaches all event handlers*/
  25434. Scene.prototype.detachControl = function () {
  25435. var engine = this.getEngine();
  25436. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25437. var canvas = engine.getRenderingCanvas();
  25438. if (!canvas) {
  25439. return;
  25440. }
  25441. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25442. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25443. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25444. if (this._onCanvasBlurObserver) {
  25445. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25446. }
  25447. if (this._onCanvasFocusObserver) {
  25448. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25449. }
  25450. // Wheel
  25451. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25452. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25453. // Keyboard
  25454. canvas.removeEventListener("keydown", this._onKeyDown);
  25455. canvas.removeEventListener("keyup", this._onKeyUp);
  25456. // Observables
  25457. this.onKeyboardObservable.clear();
  25458. this.onPreKeyboardObservable.clear();
  25459. this.onPointerObservable.clear();
  25460. this.onPrePointerObservable.clear();
  25461. };
  25462. /**
  25463. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25464. * Delay loaded resources are not taking in account
  25465. * @return true if all required resources are ready
  25466. */
  25467. Scene.prototype.isReady = function () {
  25468. if (this._isDisposed) {
  25469. return false;
  25470. }
  25471. if (this._pendingData.length > 0) {
  25472. return false;
  25473. }
  25474. var index;
  25475. var engine = this.getEngine();
  25476. // Geometries
  25477. for (index = 0; index < this.geometries.length; index++) {
  25478. var geometry = this.geometries[index];
  25479. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25480. return false;
  25481. }
  25482. }
  25483. // Meshes
  25484. for (index = 0; index < this.meshes.length; index++) {
  25485. var mesh = this.meshes[index];
  25486. if (!mesh.isEnabled()) {
  25487. continue;
  25488. }
  25489. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25490. continue;
  25491. }
  25492. if (!mesh.isReady(true)) {
  25493. return false;
  25494. }
  25495. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25496. // Is Ready For Mesh
  25497. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25498. var step = _a[_i];
  25499. if (!step.action(mesh, hardwareInstancedRendering)) {
  25500. return false;
  25501. }
  25502. }
  25503. }
  25504. // Post-processes
  25505. if (this.activeCameras && this.activeCameras.length > 0) {
  25506. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25507. var camera = _c[_b];
  25508. if (!camera.isReady(true)) {
  25509. return false;
  25510. }
  25511. }
  25512. }
  25513. else if (this.activeCamera) {
  25514. if (!this.activeCamera.isReady(true)) {
  25515. return false;
  25516. }
  25517. }
  25518. // Particles
  25519. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25520. var particleSystem = _e[_d];
  25521. if (!particleSystem.isReady()) {
  25522. return false;
  25523. }
  25524. }
  25525. return true;
  25526. };
  25527. /** Resets all cached information relative to material (including effect and visibility) */
  25528. Scene.prototype.resetCachedMaterial = function () {
  25529. this._cachedMaterial = null;
  25530. this._cachedEffect = null;
  25531. this._cachedVisibility = null;
  25532. };
  25533. /**
  25534. * Registers a function to be called before every frame render
  25535. * @param func defines the function to register
  25536. */
  25537. Scene.prototype.registerBeforeRender = function (func) {
  25538. this.onBeforeRenderObservable.add(func);
  25539. };
  25540. /**
  25541. * Unregisters a function called before every frame render
  25542. * @param func defines the function to unregister
  25543. */
  25544. Scene.prototype.unregisterBeforeRender = function (func) {
  25545. this.onBeforeRenderObservable.removeCallback(func);
  25546. };
  25547. /**
  25548. * Registers a function to be called after every frame render
  25549. * @param func defines the function to register
  25550. */
  25551. Scene.prototype.registerAfterRender = function (func) {
  25552. this.onAfterRenderObservable.add(func);
  25553. };
  25554. /**
  25555. * Unregisters a function called after every frame render
  25556. * @param func defines the function to unregister
  25557. */
  25558. Scene.prototype.unregisterAfterRender = function (func) {
  25559. this.onAfterRenderObservable.removeCallback(func);
  25560. };
  25561. Scene.prototype._executeOnceBeforeRender = function (func) {
  25562. var _this = this;
  25563. var execFunc = function () {
  25564. func();
  25565. setTimeout(function () {
  25566. _this.unregisterBeforeRender(execFunc);
  25567. });
  25568. };
  25569. this.registerBeforeRender(execFunc);
  25570. };
  25571. /**
  25572. * The provided function will run before render once and will be disposed afterwards.
  25573. * A timeout delay can be provided so that the function will be executed in N ms.
  25574. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25575. * @param func The function to be executed.
  25576. * @param timeout optional delay in ms
  25577. */
  25578. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25579. var _this = this;
  25580. if (timeout !== undefined) {
  25581. setTimeout(function () {
  25582. _this._executeOnceBeforeRender(func);
  25583. }, timeout);
  25584. }
  25585. else {
  25586. this._executeOnceBeforeRender(func);
  25587. }
  25588. };
  25589. /** @hidden */
  25590. Scene.prototype._addPendingData = function (data) {
  25591. this._pendingData.push(data);
  25592. };
  25593. /** @hidden */
  25594. Scene.prototype._removePendingData = function (data) {
  25595. var wasLoading = this.isLoading;
  25596. var index = this._pendingData.indexOf(data);
  25597. if (index !== -1) {
  25598. this._pendingData.splice(index, 1);
  25599. }
  25600. if (wasLoading && !this.isLoading) {
  25601. this.onDataLoadedObservable.notifyObservers(this);
  25602. }
  25603. };
  25604. /**
  25605. * Returns the number of items waiting to be loaded
  25606. * @returns the number of items waiting to be loaded
  25607. */
  25608. Scene.prototype.getWaitingItemsCount = function () {
  25609. return this._pendingData.length;
  25610. };
  25611. Object.defineProperty(Scene.prototype, "isLoading", {
  25612. /**
  25613. * Returns a boolean indicating if the scene is still loading data
  25614. */
  25615. get: function () {
  25616. return this._pendingData.length > 0;
  25617. },
  25618. enumerable: true,
  25619. configurable: true
  25620. });
  25621. /**
  25622. * Registers a function to be executed when the scene is ready
  25623. * @param {Function} func - the function to be executed
  25624. */
  25625. Scene.prototype.executeWhenReady = function (func) {
  25626. var _this = this;
  25627. this.onReadyObservable.add(func);
  25628. if (this._executeWhenReadyTimeoutId !== -1) {
  25629. return;
  25630. }
  25631. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25632. _this._checkIsReady();
  25633. }, 150);
  25634. };
  25635. /**
  25636. * Returns a promise that resolves when the scene is ready
  25637. * @returns A promise that resolves when the scene is ready
  25638. */
  25639. Scene.prototype.whenReadyAsync = function () {
  25640. var _this = this;
  25641. return new Promise(function (resolve) {
  25642. _this.executeWhenReady(function () {
  25643. resolve();
  25644. });
  25645. });
  25646. };
  25647. /** @hidden */
  25648. Scene.prototype._checkIsReady = function () {
  25649. var _this = this;
  25650. this._registerTransientComponents();
  25651. if (this.isReady()) {
  25652. this.onReadyObservable.notifyObservers(this);
  25653. this.onReadyObservable.clear();
  25654. this._executeWhenReadyTimeoutId = -1;
  25655. return;
  25656. }
  25657. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25658. _this._checkIsReady();
  25659. }, 150);
  25660. };
  25661. // Animations
  25662. /**
  25663. * Will start the animation sequence of a given target
  25664. * @param target defines the target
  25665. * @param from defines from which frame should animation start
  25666. * @param to defines until which frame should animation run.
  25667. * @param weight defines the weight to apply to the animation (1.0 by default)
  25668. * @param loop defines if the animation loops
  25669. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25670. * @param onAnimationEnd defines the function to be executed when the animation ends
  25671. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25672. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25673. * @returns the animatable object created for this animation
  25674. */
  25675. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25676. if (weight === void 0) { weight = 1.0; }
  25677. if (speedRatio === void 0) { speedRatio = 1.0; }
  25678. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25679. returnedAnimatable.weight = weight;
  25680. return returnedAnimatable;
  25681. };
  25682. /**
  25683. * Will start the animation sequence of a given target
  25684. * @param target defines the target
  25685. * @param from defines from which frame should animation start
  25686. * @param to defines until which frame should animation run.
  25687. * @param loop defines if the animation loops
  25688. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25689. * @param onAnimationEnd defines the function to be executed when the animation ends
  25690. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25691. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25692. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25693. * @returns the animatable object created for this animation
  25694. */
  25695. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25696. if (speedRatio === void 0) { speedRatio = 1.0; }
  25697. if (stopCurrent === void 0) { stopCurrent = true; }
  25698. if (from > to && speedRatio > 0) {
  25699. speedRatio *= -1;
  25700. }
  25701. if (stopCurrent) {
  25702. this.stopAnimation(target, undefined, targetMask);
  25703. }
  25704. if (!animatable) {
  25705. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25706. }
  25707. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25708. // Local animations
  25709. if (target.animations && shouldRunTargetAnimations) {
  25710. animatable.appendAnimations(target, target.animations);
  25711. }
  25712. // Children animations
  25713. if (target.getAnimatables) {
  25714. var animatables = target.getAnimatables();
  25715. for (var index = 0; index < animatables.length; index++) {
  25716. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25717. }
  25718. }
  25719. animatable.reset();
  25720. return animatable;
  25721. };
  25722. /**
  25723. * Begin a new animation on a given node
  25724. * @param target defines the target where the animation will take place
  25725. * @param animations defines the list of animations to start
  25726. * @param from defines the initial value
  25727. * @param to defines the final value
  25728. * @param loop defines if you want animation to loop (off by default)
  25729. * @param speedRatio defines the speed ratio to apply to all animations
  25730. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25731. * @returns the list of created animatables
  25732. */
  25733. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25734. if (speedRatio === undefined) {
  25735. speedRatio = 1.0;
  25736. }
  25737. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25738. return animatable;
  25739. };
  25740. /**
  25741. * Begin a new animation on a given node and its hierarchy
  25742. * @param target defines the root node where the animation will take place
  25743. * @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.
  25744. * @param animations defines the list of animations to start
  25745. * @param from defines the initial value
  25746. * @param to defines the final value
  25747. * @param loop defines if you want animation to loop (off by default)
  25748. * @param speedRatio defines the speed ratio to apply to all animations
  25749. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25750. * @returns the list of animatables created for all nodes
  25751. */
  25752. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25753. var children = target.getDescendants(directDescendantsOnly);
  25754. var result = [];
  25755. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25756. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25757. var child = children_1[_i];
  25758. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25759. }
  25760. return result;
  25761. };
  25762. /**
  25763. * Gets the animatable associated with a specific target
  25764. * @param target defines the target of the animatable
  25765. * @returns the required animatable if found
  25766. */
  25767. Scene.prototype.getAnimatableByTarget = function (target) {
  25768. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25769. if (this._activeAnimatables[index].target === target) {
  25770. return this._activeAnimatables[index];
  25771. }
  25772. }
  25773. return null;
  25774. };
  25775. /**
  25776. * Gets all animatables associated with a given target
  25777. * @param target defines the target to look animatables for
  25778. * @returns an array of Animatables
  25779. */
  25780. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25781. var result = [];
  25782. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25783. if (this._activeAnimatables[index].target === target) {
  25784. result.push(this._activeAnimatables[index]);
  25785. }
  25786. }
  25787. return result;
  25788. };
  25789. Object.defineProperty(Scene.prototype, "animatables", {
  25790. /**
  25791. * Gets all animatable attached to the scene
  25792. */
  25793. get: function () {
  25794. return this._activeAnimatables;
  25795. },
  25796. enumerable: true,
  25797. configurable: true
  25798. });
  25799. /**
  25800. * Will stop the animation of the given target
  25801. * @param target - the target
  25802. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25803. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  25804. */
  25805. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25806. var animatables = this.getAllAnimatablesByTarget(target);
  25807. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25808. var animatable = animatables_1[_i];
  25809. animatable.stop(animationName, targetMask);
  25810. }
  25811. };
  25812. /**
  25813. * Stops and removes all animations that have been applied to the scene
  25814. */
  25815. Scene.prototype.stopAllAnimations = function () {
  25816. if (this._activeAnimatables) {
  25817. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25818. this._activeAnimatables[i].stop();
  25819. }
  25820. this._activeAnimatables = [];
  25821. }
  25822. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25823. var group = _a[_i];
  25824. group.stop();
  25825. }
  25826. };
  25827. Scene.prototype._animate = function () {
  25828. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25829. return;
  25830. }
  25831. // Getting time
  25832. var now = BABYLON.Tools.Now;
  25833. if (!this._animationTimeLast) {
  25834. if (this._pendingData.length > 0) {
  25835. return;
  25836. }
  25837. this._animationTimeLast = now;
  25838. }
  25839. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25840. this._animationTime += deltaTime;
  25841. this._animationTimeLast = now;
  25842. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25843. this._activeAnimatables[index]._animate(this._animationTime);
  25844. }
  25845. // Late animation bindings
  25846. this._processLateAnimationBindings();
  25847. };
  25848. /** @hidden */
  25849. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25850. var target = runtimeAnimation.target;
  25851. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25852. if (!target._lateAnimationHolders) {
  25853. target._lateAnimationHolders = {};
  25854. }
  25855. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25856. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25857. totalWeight: 0,
  25858. animations: [],
  25859. originalValue: originalValue
  25860. };
  25861. }
  25862. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25863. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25864. };
  25865. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25866. var normalizer = 1.0;
  25867. var finalPosition = BABYLON.Tmp.Vector3[0];
  25868. var finalScaling = BABYLON.Tmp.Vector3[1];
  25869. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25870. var startIndex = 0;
  25871. var originalAnimation = holder.animations[0];
  25872. var originalValue = holder.originalValue;
  25873. var scale = 1;
  25874. if (holder.totalWeight < 1.0) {
  25875. // We need to mix the original value in
  25876. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25877. scale = 1.0 - holder.totalWeight;
  25878. }
  25879. else {
  25880. startIndex = 1;
  25881. // We need to normalize the weights
  25882. normalizer = holder.totalWeight;
  25883. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25884. scale = originalAnimation.weight / normalizer;
  25885. if (scale == 1) {
  25886. return originalAnimation.currentValue;
  25887. }
  25888. }
  25889. finalScaling.scaleInPlace(scale);
  25890. finalPosition.scaleInPlace(scale);
  25891. finalQuaternion.scaleInPlace(scale);
  25892. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25893. var runtimeAnimation = holder.animations[animIndex];
  25894. var scale = runtimeAnimation.weight / normalizer;
  25895. var currentPosition = BABYLON.Tmp.Vector3[2];
  25896. var currentScaling = BABYLON.Tmp.Vector3[3];
  25897. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25898. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25899. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25900. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25901. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25902. }
  25903. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25904. return originalAnimation._workValue;
  25905. };
  25906. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25907. var originalAnimation = holder.animations[0];
  25908. var originalValue = holder.originalValue;
  25909. if (holder.animations.length === 1) {
  25910. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25911. }
  25912. var normalizer = 1.0;
  25913. var quaternions;
  25914. var weights;
  25915. if (holder.totalWeight < 1.0) {
  25916. var scale = 1.0 - holder.totalWeight;
  25917. quaternions = [];
  25918. weights = [];
  25919. quaternions.push(originalValue);
  25920. weights.push(scale);
  25921. }
  25922. else {
  25923. if (holder.animations.length === 2) { // Slerp as soon as we can
  25924. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25925. }
  25926. quaternions = [];
  25927. weights = [];
  25928. normalizer = holder.totalWeight;
  25929. }
  25930. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25931. var runtimeAnimation = holder.animations[animIndex];
  25932. quaternions.push(runtimeAnimation.currentValue);
  25933. weights.push(runtimeAnimation.weight / normalizer);
  25934. }
  25935. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25936. var cumulativeAmount = 0;
  25937. var cumulativeQuaternion = null;
  25938. for (var index = 0; index < quaternions.length;) {
  25939. if (!cumulativeQuaternion) {
  25940. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25941. cumulativeAmount = weights[index] + weights[index + 1];
  25942. index += 2;
  25943. continue;
  25944. }
  25945. cumulativeAmount += weights[index];
  25946. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25947. index++;
  25948. }
  25949. return cumulativeQuaternion;
  25950. };
  25951. Scene.prototype._processLateAnimationBindings = function () {
  25952. if (!this._registeredForLateAnimationBindings.length) {
  25953. return;
  25954. }
  25955. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25956. var target = this._registeredForLateAnimationBindings.data[index];
  25957. for (var path in target._lateAnimationHolders) {
  25958. var holder = target._lateAnimationHolders[path];
  25959. var originalAnimation = holder.animations[0];
  25960. var originalValue = holder.originalValue;
  25961. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25962. var finalValue = void 0;
  25963. if (matrixDecomposeMode) {
  25964. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25965. }
  25966. else {
  25967. var quaternionMode = originalValue.w !== undefined;
  25968. if (quaternionMode) {
  25969. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25970. }
  25971. else {
  25972. var startIndex = 0;
  25973. var normalizer = 1.0;
  25974. if (holder.totalWeight < 1.0) {
  25975. // We need to mix the original value in
  25976. if (originalValue.scale) {
  25977. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25978. }
  25979. else {
  25980. finalValue = originalValue * (1.0 - holder.totalWeight);
  25981. }
  25982. }
  25983. else {
  25984. // We need to normalize the weights
  25985. normalizer = holder.totalWeight;
  25986. var scale_1 = originalAnimation.weight / normalizer;
  25987. if (scale_1 !== 1) {
  25988. if (originalAnimation.currentValue.scale) {
  25989. finalValue = originalAnimation.currentValue.scale(scale_1);
  25990. }
  25991. else {
  25992. finalValue = originalAnimation.currentValue * scale_1;
  25993. }
  25994. }
  25995. else {
  25996. finalValue = originalAnimation.currentValue;
  25997. }
  25998. startIndex = 1;
  25999. }
  26000. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26001. var runtimeAnimation = holder.animations[animIndex];
  26002. var scale = runtimeAnimation.weight / normalizer;
  26003. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26004. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26005. }
  26006. else {
  26007. finalValue += runtimeAnimation.currentValue * scale;
  26008. }
  26009. }
  26010. }
  26011. }
  26012. target[path] = finalValue;
  26013. }
  26014. target._lateAnimationHolders = {};
  26015. }
  26016. this._registeredForLateAnimationBindings.reset();
  26017. };
  26018. // Matrix
  26019. /** @hidden */
  26020. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26021. this._useAlternateCameraConfiguration = active;
  26022. };
  26023. /**
  26024. * Gets the current view matrix
  26025. * @returns a Matrix
  26026. */
  26027. Scene.prototype.getViewMatrix = function () {
  26028. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26029. };
  26030. /**
  26031. * Gets the current projection matrix
  26032. * @returns a Matrix
  26033. */
  26034. Scene.prototype.getProjectionMatrix = function () {
  26035. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26036. };
  26037. /**
  26038. * Gets the current transform matrix
  26039. * @returns a Matrix made of View * Projection
  26040. */
  26041. Scene.prototype.getTransformMatrix = function () {
  26042. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26043. };
  26044. /**
  26045. * Sets the current transform matrix
  26046. * @param view defines the View matrix to use
  26047. * @param projection defines the Projection matrix to use
  26048. */
  26049. Scene.prototype.setTransformMatrix = function (view, projection) {
  26050. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26051. return;
  26052. }
  26053. this._viewUpdateFlag = view.updateFlag;
  26054. this._projectionUpdateFlag = projection.updateFlag;
  26055. this._viewMatrix = view;
  26056. this._projectionMatrix = projection;
  26057. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26058. // Update frustum
  26059. if (!this._frustumPlanes) {
  26060. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26061. }
  26062. else {
  26063. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26064. }
  26065. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26066. var otherCamera = this.activeCamera._alternateCamera;
  26067. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26068. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26069. }
  26070. if (this._sceneUbo.useUbo) {
  26071. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26072. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26073. this._sceneUbo.update();
  26074. }
  26075. };
  26076. /** @hidden */
  26077. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26078. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26079. return;
  26080. }
  26081. this._alternateViewUpdateFlag = view.updateFlag;
  26082. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26083. this._alternateViewMatrix = view;
  26084. this._alternateProjectionMatrix = projection;
  26085. if (!this._alternateTransformMatrix) {
  26086. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26087. }
  26088. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26089. if (!this._alternateSceneUbo) {
  26090. this._createAlternateUbo();
  26091. }
  26092. if (this._alternateSceneUbo.useUbo) {
  26093. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26094. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26095. this._alternateSceneUbo.update();
  26096. }
  26097. };
  26098. /**
  26099. * Gets the uniform buffer used to store scene data
  26100. * @returns a UniformBuffer
  26101. */
  26102. Scene.prototype.getSceneUniformBuffer = function () {
  26103. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26104. };
  26105. /**
  26106. * Gets an unique (relatively to the current scene) Id
  26107. * @returns an unique number for the scene
  26108. */
  26109. Scene.prototype.getUniqueId = function () {
  26110. var result = Scene._uniqueIdCounter;
  26111. Scene._uniqueIdCounter++;
  26112. return result;
  26113. };
  26114. /**
  26115. * Add a mesh to the list of scene's meshes
  26116. * @param newMesh defines the mesh to add
  26117. * @param recursive if all child meshes should also be added to the scene
  26118. */
  26119. Scene.prototype.addMesh = function (newMesh, recursive) {
  26120. var _this = this;
  26121. if (recursive === void 0) { recursive = false; }
  26122. this.meshes.push(newMesh);
  26123. //notify the collision coordinator
  26124. if (this.collisionCoordinator) {
  26125. this.collisionCoordinator.onMeshAdded(newMesh);
  26126. }
  26127. newMesh._resyncLightSources();
  26128. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26129. if (recursive) {
  26130. newMesh.getChildMeshes().forEach(function (m) {
  26131. _this.addMesh(m);
  26132. });
  26133. }
  26134. };
  26135. /**
  26136. * Remove a mesh for the list of scene's meshes
  26137. * @param toRemove defines the mesh to remove
  26138. * @param recursive if all child meshes should also be removed from the scene
  26139. * @returns the index where the mesh was in the mesh list
  26140. */
  26141. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26142. var _this = this;
  26143. if (recursive === void 0) { recursive = false; }
  26144. var index = this.meshes.indexOf(toRemove);
  26145. if (index !== -1) {
  26146. // Remove from the scene if mesh found
  26147. this.meshes.splice(index, 1);
  26148. }
  26149. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26150. if (recursive) {
  26151. toRemove.getChildMeshes().forEach(function (m) {
  26152. _this.removeMesh(m);
  26153. });
  26154. }
  26155. return index;
  26156. };
  26157. /**
  26158. * Add a transform node to the list of scene's transform nodes
  26159. * @param newTransformNode defines the transform node to add
  26160. */
  26161. Scene.prototype.addTransformNode = function (newTransformNode) {
  26162. this.transformNodes.push(newTransformNode);
  26163. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26164. };
  26165. /**
  26166. * Remove a transform node for the list of scene's transform nodes
  26167. * @param toRemove defines the transform node to remove
  26168. * @returns the index where the transform node was in the transform node list
  26169. */
  26170. Scene.prototype.removeTransformNode = function (toRemove) {
  26171. var index = this.transformNodes.indexOf(toRemove);
  26172. if (index !== -1) {
  26173. // Remove from the scene if found
  26174. this.transformNodes.splice(index, 1);
  26175. }
  26176. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26177. return index;
  26178. };
  26179. /**
  26180. * Remove a skeleton for the list of scene's skeletons
  26181. * @param toRemove defines the skeleton to remove
  26182. * @returns the index where the skeleton was in the skeleton list
  26183. */
  26184. Scene.prototype.removeSkeleton = function (toRemove) {
  26185. var index = this.skeletons.indexOf(toRemove);
  26186. if (index !== -1) {
  26187. // Remove from the scene if found
  26188. this.skeletons.splice(index, 1);
  26189. }
  26190. return index;
  26191. };
  26192. /**
  26193. * Remove a morph target for the list of scene's morph targets
  26194. * @param toRemove defines the morph target to remove
  26195. * @returns the index where the morph target was in the morph target list
  26196. */
  26197. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26198. var index = this.morphTargetManagers.indexOf(toRemove);
  26199. if (index !== -1) {
  26200. // Remove from the scene if found
  26201. this.morphTargetManagers.splice(index, 1);
  26202. }
  26203. return index;
  26204. };
  26205. /**
  26206. * Remove a light for the list of scene's lights
  26207. * @param toRemove defines the light to remove
  26208. * @returns the index where the light was in the light list
  26209. */
  26210. Scene.prototype.removeLight = function (toRemove) {
  26211. var index = this.lights.indexOf(toRemove);
  26212. if (index !== -1) {
  26213. // Remove from meshes
  26214. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26215. var mesh = _a[_i];
  26216. mesh._removeLightSource(toRemove);
  26217. }
  26218. // Remove from the scene if mesh found
  26219. this.lights.splice(index, 1);
  26220. this.sortLightsByPriority();
  26221. }
  26222. this.onLightRemovedObservable.notifyObservers(toRemove);
  26223. return index;
  26224. };
  26225. /**
  26226. * Remove a camera for the list of scene's cameras
  26227. * @param toRemove defines the camera to remove
  26228. * @returns the index where the camera was in the camera list
  26229. */
  26230. Scene.prototype.removeCamera = function (toRemove) {
  26231. var index = this.cameras.indexOf(toRemove);
  26232. if (index !== -1) {
  26233. // Remove from the scene if mesh found
  26234. this.cameras.splice(index, 1);
  26235. }
  26236. // Remove from activeCameras
  26237. var index2 = this.activeCameras.indexOf(toRemove);
  26238. if (index2 !== -1) {
  26239. // Remove from the scene if mesh found
  26240. this.activeCameras.splice(index2, 1);
  26241. }
  26242. // Reset the activeCamera
  26243. if (this.activeCamera === toRemove) {
  26244. if (this.cameras.length > 0) {
  26245. this.activeCamera = this.cameras[0];
  26246. }
  26247. else {
  26248. this.activeCamera = null;
  26249. }
  26250. }
  26251. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26252. return index;
  26253. };
  26254. /**
  26255. * Remove a particle system for the list of scene's particle systems
  26256. * @param toRemove defines the particle system to remove
  26257. * @returns the index where the particle system was in the particle system list
  26258. */
  26259. Scene.prototype.removeParticleSystem = function (toRemove) {
  26260. var index = this.particleSystems.indexOf(toRemove);
  26261. if (index !== -1) {
  26262. this.particleSystems.splice(index, 1);
  26263. }
  26264. return index;
  26265. };
  26266. /**
  26267. * Remove a animation for the list of scene's animations
  26268. * @param toRemove defines the animation to remove
  26269. * @returns the index where the animation was in the animation list
  26270. */
  26271. Scene.prototype.removeAnimation = function (toRemove) {
  26272. var index = this.animations.indexOf(toRemove);
  26273. if (index !== -1) {
  26274. this.animations.splice(index, 1);
  26275. }
  26276. return index;
  26277. };
  26278. /**
  26279. * Removes the given animation group from this scene.
  26280. * @param toRemove The animation group to remove
  26281. * @returns The index of the removed animation group
  26282. */
  26283. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26284. var index = this.animationGroups.indexOf(toRemove);
  26285. if (index !== -1) {
  26286. this.animationGroups.splice(index, 1);
  26287. }
  26288. return index;
  26289. };
  26290. /**
  26291. * Removes the given multi-material from this scene.
  26292. * @param toRemove The multi-material to remove
  26293. * @returns The index of the removed multi-material
  26294. */
  26295. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26296. var index = this.multiMaterials.indexOf(toRemove);
  26297. if (index !== -1) {
  26298. this.multiMaterials.splice(index, 1);
  26299. }
  26300. return index;
  26301. };
  26302. /**
  26303. * Removes the given material from this scene.
  26304. * @param toRemove The material to remove
  26305. * @returns The index of the removed material
  26306. */
  26307. Scene.prototype.removeMaterial = function (toRemove) {
  26308. var index = this.materials.indexOf(toRemove);
  26309. if (index !== -1) {
  26310. this.materials.splice(index, 1);
  26311. }
  26312. return index;
  26313. };
  26314. /**
  26315. * Removes the given action manager from this scene.
  26316. * @param toRemove The action manager to remove
  26317. * @returns The index of the removed action manager
  26318. */
  26319. Scene.prototype.removeActionManager = function (toRemove) {
  26320. var index = this.actionManagers.indexOf(toRemove);
  26321. if (index !== -1) {
  26322. this.actionManagers.splice(index, 1);
  26323. }
  26324. return index;
  26325. };
  26326. /**
  26327. * Removes the given texture from this scene.
  26328. * @param toRemove The texture to remove
  26329. * @returns The index of the removed texture
  26330. */
  26331. Scene.prototype.removeTexture = function (toRemove) {
  26332. var index = this.textures.indexOf(toRemove);
  26333. if (index !== -1) {
  26334. this.textures.splice(index, 1);
  26335. }
  26336. return index;
  26337. };
  26338. /**
  26339. * Adds the given light to this scene
  26340. * @param newLight The light to add
  26341. */
  26342. Scene.prototype.addLight = function (newLight) {
  26343. this.lights.push(newLight);
  26344. this.sortLightsByPriority();
  26345. // Add light to all meshes (To support if the light is removed and then readded)
  26346. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26347. var mesh = _a[_i];
  26348. if (mesh._lightSources.indexOf(newLight) === -1) {
  26349. mesh._lightSources.push(newLight);
  26350. mesh._resyncLightSources();
  26351. }
  26352. }
  26353. this.onNewLightAddedObservable.notifyObservers(newLight);
  26354. };
  26355. /**
  26356. * Sorts the list list based on light priorities
  26357. */
  26358. Scene.prototype.sortLightsByPriority = function () {
  26359. if (this.requireLightSorting) {
  26360. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26361. }
  26362. };
  26363. /**
  26364. * Adds the given camera to this scene
  26365. * @param newCamera The camera to add
  26366. */
  26367. Scene.prototype.addCamera = function (newCamera) {
  26368. this.cameras.push(newCamera);
  26369. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26370. };
  26371. /**
  26372. * Adds the given skeleton to this scene
  26373. * @param newSkeleton The skeleton to add
  26374. */
  26375. Scene.prototype.addSkeleton = function (newSkeleton) {
  26376. this.skeletons.push(newSkeleton);
  26377. };
  26378. /**
  26379. * Adds the given particle system to this scene
  26380. * @param newParticleSystem The particle system to add
  26381. */
  26382. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26383. this.particleSystems.push(newParticleSystem);
  26384. };
  26385. /**
  26386. * Adds the given animation to this scene
  26387. * @param newAnimation The animation to add
  26388. */
  26389. Scene.prototype.addAnimation = function (newAnimation) {
  26390. this.animations.push(newAnimation);
  26391. };
  26392. /**
  26393. * Adds the given animation group to this scene.
  26394. * @param newAnimationGroup The animation group to add
  26395. */
  26396. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26397. this.animationGroups.push(newAnimationGroup);
  26398. };
  26399. /**
  26400. * Adds the given multi-material to this scene
  26401. * @param newMultiMaterial The multi-material to add
  26402. */
  26403. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26404. this.multiMaterials.push(newMultiMaterial);
  26405. };
  26406. /**
  26407. * Adds the given material to this scene
  26408. * @param newMaterial The material to add
  26409. */
  26410. Scene.prototype.addMaterial = function (newMaterial) {
  26411. this.materials.push(newMaterial);
  26412. };
  26413. /**
  26414. * Adds the given morph target to this scene
  26415. * @param newMorphTargetManager The morph target to add
  26416. */
  26417. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26418. this.morphTargetManagers.push(newMorphTargetManager);
  26419. };
  26420. /**
  26421. * Adds the given geometry to this scene
  26422. * @param newGeometry The geometry to add
  26423. */
  26424. Scene.prototype.addGeometry = function (newGeometry) {
  26425. this.geometries.push(newGeometry);
  26426. };
  26427. /**
  26428. * Adds the given action manager to this scene
  26429. * @param newActionManager The action manager to add
  26430. */
  26431. Scene.prototype.addActionManager = function (newActionManager) {
  26432. this.actionManagers.push(newActionManager);
  26433. };
  26434. /**
  26435. * Adds the given texture to this scene.
  26436. * @param newTexture The texture to add
  26437. */
  26438. Scene.prototype.addTexture = function (newTexture) {
  26439. this.textures.push(newTexture);
  26440. };
  26441. /**
  26442. * Switch active camera
  26443. * @param newCamera defines the new active camera
  26444. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26445. */
  26446. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26447. if (attachControl === void 0) { attachControl = true; }
  26448. var canvas = this._engine.getRenderingCanvas();
  26449. if (!canvas) {
  26450. return;
  26451. }
  26452. if (this.activeCamera) {
  26453. this.activeCamera.detachControl(canvas);
  26454. }
  26455. this.activeCamera = newCamera;
  26456. if (attachControl) {
  26457. newCamera.attachControl(canvas);
  26458. }
  26459. };
  26460. /**
  26461. * sets the active camera of the scene using its ID
  26462. * @param id defines the camera's ID
  26463. * @return the new active camera or null if none found.
  26464. */
  26465. Scene.prototype.setActiveCameraByID = function (id) {
  26466. var camera = this.getCameraByID(id);
  26467. if (camera) {
  26468. this.activeCamera = camera;
  26469. return camera;
  26470. }
  26471. return null;
  26472. };
  26473. /**
  26474. * sets the active camera of the scene using its name
  26475. * @param name defines the camera's name
  26476. * @returns the new active camera or null if none found.
  26477. */
  26478. Scene.prototype.setActiveCameraByName = function (name) {
  26479. var camera = this.getCameraByName(name);
  26480. if (camera) {
  26481. this.activeCamera = camera;
  26482. return camera;
  26483. }
  26484. return null;
  26485. };
  26486. /**
  26487. * get an animation group using its name
  26488. * @param name defines the material's name
  26489. * @return the animation group or null if none found.
  26490. */
  26491. Scene.prototype.getAnimationGroupByName = function (name) {
  26492. for (var index = 0; index < this.animationGroups.length; index++) {
  26493. if (this.animationGroups[index].name === name) {
  26494. return this.animationGroups[index];
  26495. }
  26496. }
  26497. return null;
  26498. };
  26499. /**
  26500. * get a material using its id
  26501. * @param id defines the material's ID
  26502. * @return the material or null if none found.
  26503. */
  26504. Scene.prototype.getMaterialByID = function (id) {
  26505. for (var index = 0; index < this.materials.length; index++) {
  26506. if (this.materials[index].id === id) {
  26507. return this.materials[index];
  26508. }
  26509. }
  26510. return null;
  26511. };
  26512. /**
  26513. * Gets a material using its name
  26514. * @param name defines the material's name
  26515. * @return the material or null if none found.
  26516. */
  26517. Scene.prototype.getMaterialByName = function (name) {
  26518. for (var index = 0; index < this.materials.length; index++) {
  26519. if (this.materials[index].name === name) {
  26520. return this.materials[index];
  26521. }
  26522. }
  26523. return null;
  26524. };
  26525. /**
  26526. * Gets a camera using its id
  26527. * @param id defines the id to look for
  26528. * @returns the camera or null if not found
  26529. */
  26530. Scene.prototype.getCameraByID = function (id) {
  26531. for (var index = 0; index < this.cameras.length; index++) {
  26532. if (this.cameras[index].id === id) {
  26533. return this.cameras[index];
  26534. }
  26535. }
  26536. return null;
  26537. };
  26538. /**
  26539. * Gets a camera using its unique id
  26540. * @param uniqueId defines the unique id to look for
  26541. * @returns the camera or null if not found
  26542. */
  26543. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26544. for (var index = 0; index < this.cameras.length; index++) {
  26545. if (this.cameras[index].uniqueId === uniqueId) {
  26546. return this.cameras[index];
  26547. }
  26548. }
  26549. return null;
  26550. };
  26551. /**
  26552. * Gets a camera using its name
  26553. * @param name defines the camera's name
  26554. * @return the camera or null if none found.
  26555. */
  26556. Scene.prototype.getCameraByName = function (name) {
  26557. for (var index = 0; index < this.cameras.length; index++) {
  26558. if (this.cameras[index].name === name) {
  26559. return this.cameras[index];
  26560. }
  26561. }
  26562. return null;
  26563. };
  26564. /**
  26565. * Gets a bone using its id
  26566. * @param id defines the bone's id
  26567. * @return the bone or null if not found
  26568. */
  26569. Scene.prototype.getBoneByID = function (id) {
  26570. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26571. var skeleton = this.skeletons[skeletonIndex];
  26572. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26573. if (skeleton.bones[boneIndex].id === id) {
  26574. return skeleton.bones[boneIndex];
  26575. }
  26576. }
  26577. }
  26578. return null;
  26579. };
  26580. /**
  26581. * Gets a bone using its id
  26582. * @param name defines the bone's name
  26583. * @return the bone or null if not found
  26584. */
  26585. Scene.prototype.getBoneByName = function (name) {
  26586. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26587. var skeleton = this.skeletons[skeletonIndex];
  26588. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26589. if (skeleton.bones[boneIndex].name === name) {
  26590. return skeleton.bones[boneIndex];
  26591. }
  26592. }
  26593. }
  26594. return null;
  26595. };
  26596. /**
  26597. * Gets a light node using its name
  26598. * @param name defines the the light's name
  26599. * @return the light or null if none found.
  26600. */
  26601. Scene.prototype.getLightByName = function (name) {
  26602. for (var index = 0; index < this.lights.length; index++) {
  26603. if (this.lights[index].name === name) {
  26604. return this.lights[index];
  26605. }
  26606. }
  26607. return null;
  26608. };
  26609. /**
  26610. * Gets a light node using its id
  26611. * @param id defines the light's id
  26612. * @return the light or null if none found.
  26613. */
  26614. Scene.prototype.getLightByID = function (id) {
  26615. for (var index = 0; index < this.lights.length; index++) {
  26616. if (this.lights[index].id === id) {
  26617. return this.lights[index];
  26618. }
  26619. }
  26620. return null;
  26621. };
  26622. /**
  26623. * Gets a light node using its scene-generated unique ID
  26624. * @param uniqueId defines the light's unique id
  26625. * @return the light or null if none found.
  26626. */
  26627. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26628. for (var index = 0; index < this.lights.length; index++) {
  26629. if (this.lights[index].uniqueId === uniqueId) {
  26630. return this.lights[index];
  26631. }
  26632. }
  26633. return null;
  26634. };
  26635. /**
  26636. * Gets a particle system by id
  26637. * @param id defines the particle system id
  26638. * @return the corresponding system or null if none found
  26639. */
  26640. Scene.prototype.getParticleSystemByID = function (id) {
  26641. for (var index = 0; index < this.particleSystems.length; index++) {
  26642. if (this.particleSystems[index].id === id) {
  26643. return this.particleSystems[index];
  26644. }
  26645. }
  26646. return null;
  26647. };
  26648. /**
  26649. * Gets a geometry using its ID
  26650. * @param id defines the geometry's id
  26651. * @return the geometry or null if none found.
  26652. */
  26653. Scene.prototype.getGeometryByID = function (id) {
  26654. for (var index = 0; index < this.geometries.length; index++) {
  26655. if (this.geometries[index].id === id) {
  26656. return this.geometries[index];
  26657. }
  26658. }
  26659. return null;
  26660. };
  26661. /**
  26662. * Add a new geometry to this scene
  26663. * @param geometry defines the geometry to be added to the scene.
  26664. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26665. * @return a boolean defining if the geometry was added or not
  26666. */
  26667. Scene.prototype.pushGeometry = function (geometry, force) {
  26668. if (!force && this.getGeometryByID(geometry.id)) {
  26669. return false;
  26670. }
  26671. this.geometries.push(geometry);
  26672. //notify the collision coordinator
  26673. if (this.collisionCoordinator) {
  26674. this.collisionCoordinator.onGeometryAdded(geometry);
  26675. }
  26676. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26677. return true;
  26678. };
  26679. /**
  26680. * Removes an existing geometry
  26681. * @param geometry defines the geometry to be removed from the scene
  26682. * @return a boolean defining if the geometry was removed or not
  26683. */
  26684. Scene.prototype.removeGeometry = function (geometry) {
  26685. var index = this.geometries.indexOf(geometry);
  26686. if (index > -1) {
  26687. this.geometries.splice(index, 1);
  26688. //notify the collision coordinator
  26689. if (this.collisionCoordinator) {
  26690. this.collisionCoordinator.onGeometryDeleted(geometry);
  26691. }
  26692. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26693. return true;
  26694. }
  26695. return false;
  26696. };
  26697. /**
  26698. * Gets the list of geometries attached to the scene
  26699. * @returns an array of Geometry
  26700. */
  26701. Scene.prototype.getGeometries = function () {
  26702. return this.geometries;
  26703. };
  26704. /**
  26705. * Gets the first added mesh found of a given ID
  26706. * @param id defines the id to search for
  26707. * @return the mesh found or null if not found at all
  26708. */
  26709. Scene.prototype.getMeshByID = function (id) {
  26710. for (var index = 0; index < this.meshes.length; index++) {
  26711. if (this.meshes[index].id === id) {
  26712. return this.meshes[index];
  26713. }
  26714. }
  26715. return null;
  26716. };
  26717. /**
  26718. * Gets a list of meshes using their id
  26719. * @param id defines the id to search for
  26720. * @returns a list of meshes
  26721. */
  26722. Scene.prototype.getMeshesByID = function (id) {
  26723. return this.meshes.filter(function (m) {
  26724. return m.id === id;
  26725. });
  26726. };
  26727. /**
  26728. * Gets the first added transform node found of a given ID
  26729. * @param id defines the id to search for
  26730. * @return the found transform node or null if not found at all.
  26731. */
  26732. Scene.prototype.getTransformNodeByID = function (id) {
  26733. for (var index = 0; index < this.transformNodes.length; index++) {
  26734. if (this.transformNodes[index].id === id) {
  26735. return this.transformNodes[index];
  26736. }
  26737. }
  26738. return null;
  26739. };
  26740. /**
  26741. * Gets a list of transform nodes using their id
  26742. * @param id defines the id to search for
  26743. * @returns a list of transform nodes
  26744. */
  26745. Scene.prototype.getTransformNodesByID = function (id) {
  26746. return this.transformNodes.filter(function (m) {
  26747. return m.id === id;
  26748. });
  26749. };
  26750. /**
  26751. * Gets a mesh with its auto-generated unique id
  26752. * @param uniqueId defines the unique id to search for
  26753. * @return the found mesh or null if not found at all.
  26754. */
  26755. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26756. for (var index = 0; index < this.meshes.length; index++) {
  26757. if (this.meshes[index].uniqueId === uniqueId) {
  26758. return this.meshes[index];
  26759. }
  26760. }
  26761. return null;
  26762. };
  26763. /**
  26764. * Gets a the last added mesh using a given id
  26765. * @param id defines the id to search for
  26766. * @return the found mesh or null if not found at all.
  26767. */
  26768. Scene.prototype.getLastMeshByID = function (id) {
  26769. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26770. if (this.meshes[index].id === id) {
  26771. return this.meshes[index];
  26772. }
  26773. }
  26774. return null;
  26775. };
  26776. /**
  26777. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26778. * @param id defines the id to search for
  26779. * @return the found node or null if not found at all
  26780. */
  26781. Scene.prototype.getLastEntryByID = function (id) {
  26782. var index;
  26783. for (index = this.meshes.length - 1; index >= 0; index--) {
  26784. if (this.meshes[index].id === id) {
  26785. return this.meshes[index];
  26786. }
  26787. }
  26788. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26789. if (this.transformNodes[index].id === id) {
  26790. return this.transformNodes[index];
  26791. }
  26792. }
  26793. for (index = this.cameras.length - 1; index >= 0; index--) {
  26794. if (this.cameras[index].id === id) {
  26795. return this.cameras[index];
  26796. }
  26797. }
  26798. for (index = this.lights.length - 1; index >= 0; index--) {
  26799. if (this.lights[index].id === id) {
  26800. return this.lights[index];
  26801. }
  26802. }
  26803. return null;
  26804. };
  26805. /**
  26806. * Gets a node (Mesh, Camera, Light) using a given id
  26807. * @param id defines the id to search for
  26808. * @return the found node or null if not found at all
  26809. */
  26810. Scene.prototype.getNodeByID = function (id) {
  26811. var mesh = this.getMeshByID(id);
  26812. if (mesh) {
  26813. return mesh;
  26814. }
  26815. var light = this.getLightByID(id);
  26816. if (light) {
  26817. return light;
  26818. }
  26819. var camera = this.getCameraByID(id);
  26820. if (camera) {
  26821. return camera;
  26822. }
  26823. var bone = this.getBoneByID(id);
  26824. return bone;
  26825. };
  26826. /**
  26827. * Gets a node (Mesh, Camera, Light) using a given name
  26828. * @param name defines the name to search for
  26829. * @return the found node or null if not found at all.
  26830. */
  26831. Scene.prototype.getNodeByName = function (name) {
  26832. var mesh = this.getMeshByName(name);
  26833. if (mesh) {
  26834. return mesh;
  26835. }
  26836. var light = this.getLightByName(name);
  26837. if (light) {
  26838. return light;
  26839. }
  26840. var camera = this.getCameraByName(name);
  26841. if (camera) {
  26842. return camera;
  26843. }
  26844. var bone = this.getBoneByName(name);
  26845. return bone;
  26846. };
  26847. /**
  26848. * Gets a mesh using a given name
  26849. * @param name defines the name to search for
  26850. * @return the found mesh or null if not found at all.
  26851. */
  26852. Scene.prototype.getMeshByName = function (name) {
  26853. for (var index = 0; index < this.meshes.length; index++) {
  26854. if (this.meshes[index].name === name) {
  26855. return this.meshes[index];
  26856. }
  26857. }
  26858. return null;
  26859. };
  26860. /**
  26861. * Gets a transform node using a given name
  26862. * @param name defines the name to search for
  26863. * @return the found transform node or null if not found at all.
  26864. */
  26865. Scene.prototype.getTransformNodeByName = function (name) {
  26866. for (var index = 0; index < this.transformNodes.length; index++) {
  26867. if (this.transformNodes[index].name === name) {
  26868. return this.transformNodes[index];
  26869. }
  26870. }
  26871. return null;
  26872. };
  26873. /**
  26874. * Gets a sound using a given name
  26875. * @param name defines the name to search for
  26876. * @return the found sound or null if not found at all.
  26877. */
  26878. Scene.prototype.getSoundByName = function (name) {
  26879. var index;
  26880. if (BABYLON.AudioEngine) {
  26881. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26882. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26883. return this.mainSoundTrack.soundCollection[index];
  26884. }
  26885. }
  26886. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26887. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26888. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26889. return this.soundTracks[sdIndex].soundCollection[index];
  26890. }
  26891. }
  26892. }
  26893. }
  26894. return null;
  26895. };
  26896. /**
  26897. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26898. * @param id defines the id to search for
  26899. * @return the found skeleton or null if not found at all.
  26900. */
  26901. Scene.prototype.getLastSkeletonByID = function (id) {
  26902. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26903. if (this.skeletons[index].id === id) {
  26904. return this.skeletons[index];
  26905. }
  26906. }
  26907. return null;
  26908. };
  26909. /**
  26910. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26911. * @param id defines the id to search for
  26912. * @return the found skeleton or null if not found at all.
  26913. */
  26914. Scene.prototype.getSkeletonById = function (id) {
  26915. for (var index = 0; index < this.skeletons.length; index++) {
  26916. if (this.skeletons[index].id === id) {
  26917. return this.skeletons[index];
  26918. }
  26919. }
  26920. return null;
  26921. };
  26922. /**
  26923. * Gets a skeleton using a given name
  26924. * @param name defines the name to search for
  26925. * @return the found skeleton or null if not found at all.
  26926. */
  26927. Scene.prototype.getSkeletonByName = function (name) {
  26928. for (var index = 0; index < this.skeletons.length; index++) {
  26929. if (this.skeletons[index].name === name) {
  26930. return this.skeletons[index];
  26931. }
  26932. }
  26933. return null;
  26934. };
  26935. /**
  26936. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26937. * @param id defines the id to search for
  26938. * @return the found morph target manager or null if not found at all.
  26939. */
  26940. Scene.prototype.getMorphTargetManagerById = function (id) {
  26941. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26942. if (this.morphTargetManagers[index].uniqueId === id) {
  26943. return this.morphTargetManagers[index];
  26944. }
  26945. }
  26946. return null;
  26947. };
  26948. /**
  26949. * Gets a boolean indicating if the given mesh is active
  26950. * @param mesh defines the mesh to look for
  26951. * @returns true if the mesh is in the active list
  26952. */
  26953. Scene.prototype.isActiveMesh = function (mesh) {
  26954. return (this._activeMeshes.indexOf(mesh) !== -1);
  26955. };
  26956. Object.defineProperty(Scene.prototype, "uid", {
  26957. /**
  26958. * Return a unique id as a string which can serve as an identifier for the scene
  26959. */
  26960. get: function () {
  26961. if (!this._uid) {
  26962. this._uid = BABYLON.Tools.RandomId();
  26963. }
  26964. return this._uid;
  26965. },
  26966. enumerable: true,
  26967. configurable: true
  26968. });
  26969. /**
  26970. * Add an externaly attached data from its key.
  26971. * This method call will fail and return false, if such key already exists.
  26972. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26973. * @param key the unique key that identifies the data
  26974. * @param data the data object to associate to the key for this Engine instance
  26975. * @return true if no such key were already present and the data was added successfully, false otherwise
  26976. */
  26977. Scene.prototype.addExternalData = function (key, data) {
  26978. if (!this._externalData) {
  26979. this._externalData = new BABYLON.StringDictionary();
  26980. }
  26981. return this._externalData.add(key, data);
  26982. };
  26983. /**
  26984. * Get an externaly attached data from its key
  26985. * @param key the unique key that identifies the data
  26986. * @return the associated data, if present (can be null), or undefined if not present
  26987. */
  26988. Scene.prototype.getExternalData = function (key) {
  26989. if (!this._externalData) {
  26990. return null;
  26991. }
  26992. return this._externalData.get(key);
  26993. };
  26994. /**
  26995. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26996. * @param key the unique key that identifies the data
  26997. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26998. * @return the associated data, can be null if the factory returned null.
  26999. */
  27000. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27001. if (!this._externalData) {
  27002. this._externalData = new BABYLON.StringDictionary();
  27003. }
  27004. return this._externalData.getOrAddWithFactory(key, factory);
  27005. };
  27006. /**
  27007. * Remove an externaly attached data from the Engine instance
  27008. * @param key the unique key that identifies the data
  27009. * @return true if the data was successfully removed, false if it doesn't exist
  27010. */
  27011. Scene.prototype.removeExternalData = function (key) {
  27012. return this._externalData.remove(key);
  27013. };
  27014. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27015. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27016. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27017. var step = _a[_i];
  27018. step.action(mesh, subMesh);
  27019. }
  27020. var material = subMesh.getMaterial();
  27021. if (material !== null && material !== undefined) {
  27022. // Render targets
  27023. if (material.getRenderTargetTextures !== undefined) {
  27024. if (this._processedMaterials.indexOf(material) === -1) {
  27025. this._processedMaterials.push(material);
  27026. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27027. }
  27028. }
  27029. // Dispatch
  27030. this._activeIndices.addCount(subMesh.indexCount, false);
  27031. this._renderingManager.dispatch(subMesh, mesh, material);
  27032. }
  27033. }
  27034. };
  27035. /**
  27036. * Clear the processed materials smart array preventing retention point in material dispose.
  27037. */
  27038. Scene.prototype.freeProcessedMaterials = function () {
  27039. this._processedMaterials.dispose();
  27040. };
  27041. /**
  27042. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27043. */
  27044. Scene.prototype.freeActiveMeshes = function () {
  27045. this._activeMeshes.dispose();
  27046. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27047. this.activeCamera._activeMeshes.dispose();
  27048. }
  27049. if (this.activeCameras) {
  27050. for (var i = 0; i < this.activeCameras.length; i++) {
  27051. var activeCamera = this.activeCameras[i];
  27052. if (activeCamera && activeCamera._activeMeshes) {
  27053. activeCamera._activeMeshes.dispose();
  27054. }
  27055. }
  27056. }
  27057. };
  27058. /**
  27059. * Clear the info related to rendering groups preventing retention points during dispose.
  27060. */
  27061. Scene.prototype.freeRenderingGroups = function () {
  27062. if (this._renderingManager) {
  27063. this._renderingManager.freeRenderingGroups();
  27064. }
  27065. if (this.textures) {
  27066. for (var i = 0; i < this.textures.length; i++) {
  27067. var texture = this.textures[i];
  27068. if (texture && texture.renderList) {
  27069. texture.freeRenderingGroups();
  27070. }
  27071. }
  27072. }
  27073. };
  27074. /** @hidden */
  27075. Scene.prototype._isInIntermediateRendering = function () {
  27076. return this._intermediateRendering;
  27077. };
  27078. /**
  27079. * Defines the current active mesh candidate provider
  27080. * @param provider defines the provider to use
  27081. */
  27082. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27083. this._activeMeshCandidateProvider = provider;
  27084. };
  27085. /**
  27086. * Gets the current active mesh candidate provider
  27087. * @returns the current active mesh candidate provider
  27088. */
  27089. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27090. return this._activeMeshCandidateProvider;
  27091. };
  27092. /**
  27093. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27094. * @returns the current scene
  27095. */
  27096. Scene.prototype.freezeActiveMeshes = function () {
  27097. if (!this.activeCamera) {
  27098. return this;
  27099. }
  27100. if (!this._frustumPlanes) {
  27101. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27102. }
  27103. this._evaluateActiveMeshes();
  27104. this._activeMeshesFrozen = true;
  27105. return this;
  27106. };
  27107. /**
  27108. * Use this function to restart evaluating active meshes on every frame
  27109. * @returns the current scene
  27110. */
  27111. Scene.prototype.unfreezeActiveMeshes = function () {
  27112. this._activeMeshesFrozen = false;
  27113. return this;
  27114. };
  27115. Scene.prototype._evaluateActiveMeshes = function () {
  27116. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27117. return;
  27118. }
  27119. if (!this.activeCamera) {
  27120. return;
  27121. }
  27122. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27123. this.activeCamera._activeMeshes.reset();
  27124. this._activeMeshes.reset();
  27125. this._renderingManager.reset();
  27126. this._processedMaterials.reset();
  27127. this._activeParticleSystems.reset();
  27128. this._activeSkeletons.reset();
  27129. this._softwareSkinnedMeshes.reset();
  27130. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27131. var step = _a[_i];
  27132. step.action();
  27133. }
  27134. // Meshes
  27135. var meshes;
  27136. var len;
  27137. var checkIsEnabled = true;
  27138. // Determine mesh candidates
  27139. if (this._activeMeshCandidateProvider !== undefined) {
  27140. // Use _activeMeshCandidateProvider
  27141. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27142. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27143. if (meshes !== undefined) {
  27144. len = meshes.length;
  27145. }
  27146. else {
  27147. len = 0;
  27148. }
  27149. }
  27150. else if (this._selectionOctree !== undefined) {
  27151. // Octree
  27152. var selection = this._selectionOctree.select(this._frustumPlanes);
  27153. meshes = selection.data;
  27154. len = selection.length;
  27155. }
  27156. else {
  27157. // Full scene traversal
  27158. len = this.meshes.length;
  27159. meshes = this.meshes;
  27160. }
  27161. // Check each mesh
  27162. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27163. mesh = meshes[meshIndex];
  27164. if (mesh.isBlocked) {
  27165. continue;
  27166. }
  27167. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27168. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27169. continue;
  27170. }
  27171. mesh.computeWorldMatrix();
  27172. // Intersections
  27173. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27174. this._meshesForIntersections.pushNoDuplicate(mesh);
  27175. }
  27176. // Switch to current LOD
  27177. meshLOD = mesh.getLOD(this.activeCamera);
  27178. if (meshLOD === undefined || meshLOD === null) {
  27179. continue;
  27180. }
  27181. mesh._preActivate();
  27182. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27183. this._activeMeshes.push(mesh);
  27184. this.activeCamera._activeMeshes.push(mesh);
  27185. mesh._activate(this._renderId);
  27186. if (meshLOD !== mesh) {
  27187. meshLOD._activate(this._renderId);
  27188. }
  27189. this._activeMesh(mesh, meshLOD);
  27190. }
  27191. }
  27192. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27193. // Particle systems
  27194. if (this.particlesEnabled) {
  27195. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27196. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27197. var particleSystem = this.particleSystems[particleIndex];
  27198. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27199. continue;
  27200. }
  27201. var emitter = particleSystem.emitter;
  27202. if (!emitter.position || emitter.isEnabled()) {
  27203. this._activeParticleSystems.push(particleSystem);
  27204. particleSystem.animate();
  27205. this._renderingManager.dispatchParticles(particleSystem);
  27206. }
  27207. }
  27208. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27209. }
  27210. };
  27211. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27212. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27213. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27214. mesh.skeleton.prepare();
  27215. }
  27216. if (!mesh.computeBonesUsingShaders) {
  27217. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27218. }
  27219. }
  27220. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27221. var step = _a[_i];
  27222. step.action(sourceMesh, mesh);
  27223. }
  27224. if (mesh !== undefined && mesh !== null
  27225. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27226. // Submeshes Octrees
  27227. var len;
  27228. var subMeshes;
  27229. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27230. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27231. len = intersections.length;
  27232. subMeshes = intersections.data;
  27233. }
  27234. else {
  27235. subMeshes = mesh.subMeshes;
  27236. len = subMeshes.length;
  27237. }
  27238. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27239. subMesh = subMeshes[subIndex];
  27240. this._evaluateSubMesh(subMesh, mesh);
  27241. }
  27242. }
  27243. };
  27244. /**
  27245. * Update the transform matrix to update from the current active camera
  27246. * @param force defines a boolean used to force the update even if cache is up to date
  27247. */
  27248. Scene.prototype.updateTransformMatrix = function (force) {
  27249. if (!this.activeCamera) {
  27250. return;
  27251. }
  27252. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27253. };
  27254. /**
  27255. * 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)
  27256. * @param alternateCamera defines the camera to use
  27257. */
  27258. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27259. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27260. };
  27261. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27262. if (camera && camera._skipRendering) {
  27263. return;
  27264. }
  27265. var engine = this._engine;
  27266. this.activeCamera = camera;
  27267. if (!this.activeCamera)
  27268. throw new Error("Active camera not set");
  27269. // Viewport
  27270. engine.setViewport(this.activeCamera.viewport);
  27271. // Camera
  27272. this.resetCachedMaterial();
  27273. this._renderId++;
  27274. this.updateTransformMatrix();
  27275. if (camera._alternateCamera) {
  27276. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27277. this._alternateRendering = true;
  27278. }
  27279. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27280. // Meshes
  27281. this._evaluateActiveMeshes();
  27282. // Software skinning
  27283. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27284. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27285. mesh.applySkeleton(mesh.skeleton);
  27286. }
  27287. // Render targets
  27288. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27289. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27290. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27291. }
  27292. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27293. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27294. }
  27295. if (this.renderTargetsEnabled) {
  27296. this._intermediateRendering = true;
  27297. if (this._renderTargets.length > 0) {
  27298. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27299. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27300. var renderTarget = this._renderTargets.data[renderIndex];
  27301. if (renderTarget._shouldRender()) {
  27302. this._renderId++;
  27303. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27304. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27305. }
  27306. }
  27307. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27308. this._renderId++;
  27309. }
  27310. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27311. var step = _a[_i];
  27312. step.action(this.activeCamera);
  27313. }
  27314. this._intermediateRendering = false;
  27315. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27316. }
  27317. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27318. // Prepare Frame
  27319. if (this.postProcessManager) {
  27320. this.postProcessManager._prepareFrame();
  27321. }
  27322. // Before Camera Draw
  27323. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27324. var step = _c[_b];
  27325. step.action(this.activeCamera);
  27326. }
  27327. // Render
  27328. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27329. this._renderingManager.render(null, null, true, true);
  27330. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27331. // After Camera Draw
  27332. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27333. var step = _e[_d];
  27334. step.action(this.activeCamera);
  27335. }
  27336. // Finalize frame
  27337. if (this.postProcessManager) {
  27338. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27339. }
  27340. // Reset some special arrays
  27341. this._renderTargets.reset();
  27342. this._alternateRendering = false;
  27343. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27344. };
  27345. Scene.prototype._processSubCameras = function (camera) {
  27346. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27347. this._renderForCamera(camera);
  27348. return;
  27349. }
  27350. // rig cameras
  27351. for (var index = 0; index < camera._rigCameras.length; index++) {
  27352. this._renderForCamera(camera._rigCameras[index], camera);
  27353. }
  27354. this.activeCamera = camera;
  27355. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27356. };
  27357. Scene.prototype._checkIntersections = function () {
  27358. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27359. var sourceMesh = this._meshesForIntersections.data[index];
  27360. if (!sourceMesh.actionManager) {
  27361. continue;
  27362. }
  27363. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27364. var action = sourceMesh.actionManager.actions[actionIndex];
  27365. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27366. var parameters = action.getTriggerParameter();
  27367. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27368. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27369. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27370. if (areIntersecting && currentIntersectionInProgress === -1) {
  27371. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27372. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27373. sourceMesh._intersectionsInProgress.push(otherMesh);
  27374. }
  27375. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27376. sourceMesh._intersectionsInProgress.push(otherMesh);
  27377. }
  27378. }
  27379. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27380. //They intersected, and now they don't.
  27381. //is this trigger an exit trigger? execute an event.
  27382. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27383. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27384. }
  27385. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27386. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27387. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27388. return otherMesh === parameterMesh;
  27389. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27390. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27391. }
  27392. }
  27393. }
  27394. }
  27395. }
  27396. };
  27397. /**
  27398. * Render the scene
  27399. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27400. */
  27401. Scene.prototype.render = function (updateCameras) {
  27402. if (updateCameras === void 0) { updateCameras = true; }
  27403. if (this.isDisposed) {
  27404. return;
  27405. }
  27406. // Register components that have been associated lately to the scene.
  27407. this._registerTransientComponents();
  27408. this._activeParticles.fetchNewFrame();
  27409. this._totalVertices.fetchNewFrame();
  27410. this._activeIndices.fetchNewFrame();
  27411. this._activeBones.fetchNewFrame();
  27412. this._meshesForIntersections.reset();
  27413. this.resetCachedMaterial();
  27414. this.onBeforeAnimationsObservable.notifyObservers(this);
  27415. // Actions
  27416. if (this.actionManager) {
  27417. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27418. }
  27419. //Simplification Queue
  27420. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27421. this.simplificationQueue.executeNext();
  27422. }
  27423. if (this._engine.isDeterministicLockStep()) {
  27424. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27425. var defaultFPS = (60.0 / 1000.0);
  27426. var defaultFrameTime = 1000 / 60; // frame time in MS
  27427. if (this._physicsEngine) {
  27428. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27429. }
  27430. var stepsTaken = 0;
  27431. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27432. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27433. internalSteps = Math.min(internalSteps, maxSubSteps);
  27434. do {
  27435. this.onBeforeStepObservable.notifyObservers(this);
  27436. // Animations
  27437. this._animationRatio = defaultFrameTime * defaultFPS;
  27438. this._animate();
  27439. this.onAfterAnimationsObservable.notifyObservers(this);
  27440. // Physics
  27441. if (this._physicsEngine) {
  27442. this.onBeforePhysicsObservable.notifyObservers(this);
  27443. this._physicsEngine._step(defaultFrameTime / 1000);
  27444. this.onAfterPhysicsObservable.notifyObservers(this);
  27445. }
  27446. this.onAfterStepObservable.notifyObservers(this);
  27447. this._currentStepId++;
  27448. stepsTaken++;
  27449. deltaTime -= defaultFrameTime;
  27450. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27451. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27452. }
  27453. else {
  27454. // Animations
  27455. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27456. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27457. this._animate();
  27458. this.onAfterAnimationsObservable.notifyObservers(this);
  27459. // Physics
  27460. if (this._physicsEngine) {
  27461. this.onBeforePhysicsObservable.notifyObservers(this);
  27462. this._physicsEngine._step(deltaTime / 1000.0);
  27463. this.onAfterPhysicsObservable.notifyObservers(this);
  27464. }
  27465. }
  27466. // Before camera update steps
  27467. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27468. var step = _a[_i];
  27469. step.action();
  27470. }
  27471. // Update Cameras
  27472. if (updateCameras) {
  27473. if (this.activeCameras.length > 0) {
  27474. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27475. var camera = this.activeCameras[cameraIndex];
  27476. camera.update();
  27477. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27478. // rig cameras
  27479. for (var index = 0; index < camera._rigCameras.length; index++) {
  27480. camera._rigCameras[index].update();
  27481. }
  27482. }
  27483. }
  27484. }
  27485. else if (this.activeCamera) {
  27486. this.activeCamera.update();
  27487. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27488. // rig cameras
  27489. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27490. this.activeCamera._rigCameras[index].update();
  27491. }
  27492. }
  27493. }
  27494. }
  27495. // Before render
  27496. this.onBeforeRenderObservable.notifyObservers(this);
  27497. // Customs render targets
  27498. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27499. var engine = this.getEngine();
  27500. var currentActiveCamera = this.activeCamera;
  27501. if (this.renderTargetsEnabled) {
  27502. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27503. this._intermediateRendering = true;
  27504. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27505. var renderTarget = this.customRenderTargets[customIndex];
  27506. if (renderTarget._shouldRender()) {
  27507. this._renderId++;
  27508. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27509. if (!this.activeCamera)
  27510. throw new Error("Active camera not set");
  27511. // Viewport
  27512. engine.setViewport(this.activeCamera.viewport);
  27513. // Camera
  27514. this.updateTransformMatrix();
  27515. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27516. }
  27517. }
  27518. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27519. this._intermediateRendering = false;
  27520. this._renderId++;
  27521. }
  27522. // Restore back buffer
  27523. if (this.customRenderTargets.length > 0) {
  27524. engine.restoreDefaultFramebuffer();
  27525. }
  27526. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27527. this.activeCamera = currentActiveCamera;
  27528. // Procedural textures
  27529. if (this.proceduralTexturesEnabled) {
  27530. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27531. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27532. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27533. if (proceduralTexture._shouldRender()) {
  27534. proceduralTexture.render();
  27535. }
  27536. }
  27537. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27538. }
  27539. // Clear
  27540. if (this.autoClearDepthAndStencil || this.autoClear) {
  27541. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27542. }
  27543. // Shadows
  27544. if (this.shadowsEnabled) {
  27545. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27546. var light = this.lights[lightIndex];
  27547. var shadowGenerator = light.getShadowGenerator();
  27548. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27549. var shadowMap = (shadowGenerator.getShadowMap());
  27550. if (this.textures.indexOf(shadowMap) !== -1) {
  27551. this._renderTargets.push(shadowMap);
  27552. }
  27553. }
  27554. }
  27555. }
  27556. // Depth renderer
  27557. for (var key in this._depthRenderer) {
  27558. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27559. }
  27560. // Geometry renderer
  27561. if (this._geometryBufferRenderer) {
  27562. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27563. }
  27564. // RenderPipeline
  27565. if (this._postProcessRenderPipelineManager) {
  27566. this._postProcessRenderPipelineManager.update();
  27567. }
  27568. // Multi-cameras?
  27569. if (this.activeCameras.length > 0) {
  27570. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27571. if (cameraIndex > 0) {
  27572. this._engine.clear(null, false, true, true);
  27573. }
  27574. this._processSubCameras(this.activeCameras[cameraIndex]);
  27575. }
  27576. }
  27577. else {
  27578. if (!this.activeCamera) {
  27579. throw new Error("No camera defined");
  27580. }
  27581. this._processSubCameras(this.activeCamera);
  27582. }
  27583. // Intersection checks
  27584. this._checkIntersections();
  27585. // Update the audio listener attached to the camera
  27586. if (BABYLON.AudioEngine) {
  27587. this._updateAudioParameters();
  27588. }
  27589. // After render
  27590. if (this.afterRender) {
  27591. this.afterRender();
  27592. }
  27593. this.onAfterRenderObservable.notifyObservers(this);
  27594. // Cleaning
  27595. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27596. var data = this._toBeDisposed.data[index];
  27597. if (data) {
  27598. data.dispose();
  27599. }
  27600. this._toBeDisposed[index] = null;
  27601. }
  27602. this._toBeDisposed.reset();
  27603. if (this.dumpNextRenderTargets) {
  27604. this.dumpNextRenderTargets = false;
  27605. }
  27606. this._activeBones.addCount(0, true);
  27607. this._activeIndices.addCount(0, true);
  27608. this._activeParticles.addCount(0, true);
  27609. };
  27610. Scene.prototype._updateAudioParameters = function () {
  27611. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27612. return;
  27613. }
  27614. var listeningCamera;
  27615. var audioEngine = BABYLON.Engine.audioEngine;
  27616. if (this.activeCameras.length > 0) {
  27617. listeningCamera = this.activeCameras[0];
  27618. }
  27619. else {
  27620. listeningCamera = this.activeCamera;
  27621. }
  27622. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27623. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27624. // for VR cameras
  27625. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27626. listeningCamera = listeningCamera.rigCameras[0];
  27627. }
  27628. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27629. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27630. cameraDirection.normalize();
  27631. // To avoid some errors on GearVR
  27632. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27633. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27634. }
  27635. var i;
  27636. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27637. var sound = this.mainSoundTrack.soundCollection[i];
  27638. if (sound.useCustomAttenuation) {
  27639. sound.updateDistanceFromListener();
  27640. }
  27641. }
  27642. for (i = 0; i < this.soundTracks.length; i++) {
  27643. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27644. sound = this.soundTracks[i].soundCollection[j];
  27645. if (sound.useCustomAttenuation) {
  27646. sound.updateDistanceFromListener();
  27647. }
  27648. }
  27649. }
  27650. }
  27651. };
  27652. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27653. // Audio
  27654. /**
  27655. * Gets or sets if audio support is enabled
  27656. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27657. */
  27658. get: function () {
  27659. return this._audioEnabled;
  27660. },
  27661. set: function (value) {
  27662. this._audioEnabled = value;
  27663. if (BABYLON.AudioEngine) {
  27664. if (this._audioEnabled) {
  27665. this._enableAudio();
  27666. }
  27667. else {
  27668. this._disableAudio();
  27669. }
  27670. }
  27671. },
  27672. enumerable: true,
  27673. configurable: true
  27674. });
  27675. Scene.prototype._disableAudio = function () {
  27676. var i;
  27677. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27678. this.mainSoundTrack.soundCollection[i].pause();
  27679. }
  27680. for (i = 0; i < this.soundTracks.length; i++) {
  27681. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27682. this.soundTracks[i].soundCollection[j].pause();
  27683. }
  27684. }
  27685. };
  27686. Scene.prototype._enableAudio = function () {
  27687. var i;
  27688. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27689. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27690. this.mainSoundTrack.soundCollection[i].play();
  27691. }
  27692. }
  27693. for (i = 0; i < this.soundTracks.length; i++) {
  27694. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27695. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27696. this.soundTracks[i].soundCollection[j].play();
  27697. }
  27698. }
  27699. }
  27700. };
  27701. Object.defineProperty(Scene.prototype, "headphone", {
  27702. /**
  27703. * Gets or sets if audio will be output to headphones
  27704. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27705. */
  27706. get: function () {
  27707. return this._headphone;
  27708. },
  27709. set: function (value) {
  27710. this._headphone = value;
  27711. if (BABYLON.AudioEngine) {
  27712. if (this._headphone) {
  27713. this._switchAudioModeForHeadphones();
  27714. }
  27715. else {
  27716. this._switchAudioModeForNormalSpeakers();
  27717. }
  27718. }
  27719. },
  27720. enumerable: true,
  27721. configurable: true
  27722. });
  27723. Scene.prototype._switchAudioModeForHeadphones = function () {
  27724. this.mainSoundTrack.switchPanningModelToHRTF();
  27725. for (var i = 0; i < this.soundTracks.length; i++) {
  27726. this.soundTracks[i].switchPanningModelToHRTF();
  27727. }
  27728. };
  27729. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27730. this.mainSoundTrack.switchPanningModelToEqualPower();
  27731. for (var i = 0; i < this.soundTracks.length; i++) {
  27732. this.soundTracks[i].switchPanningModelToEqualPower();
  27733. }
  27734. };
  27735. /**
  27736. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27737. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27738. * @returns the created depth renderer
  27739. */
  27740. Scene.prototype.enableDepthRenderer = function (camera) {
  27741. camera = camera || this.activeCamera;
  27742. if (!camera) {
  27743. throw "No camera available to enable depth renderer";
  27744. }
  27745. if (!this._depthRenderer[camera.id]) {
  27746. var textureType = 0;
  27747. if (this._engine.getCaps().textureHalfFloatRender) {
  27748. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27749. }
  27750. else if (this._engine.getCaps().textureFloatRender) {
  27751. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27752. }
  27753. else {
  27754. throw "Depth renderer does not support int texture type";
  27755. }
  27756. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27757. }
  27758. return this._depthRenderer[camera.id];
  27759. };
  27760. /**
  27761. * Disables a depth renderer for a given camera
  27762. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27763. */
  27764. Scene.prototype.disableDepthRenderer = function (camera) {
  27765. camera = camera || this.activeCamera;
  27766. if (!camera || !this._depthRenderer[camera.id]) {
  27767. return;
  27768. }
  27769. this._depthRenderer[camera.id].dispose();
  27770. delete this._depthRenderer[camera.id];
  27771. };
  27772. /**
  27773. * Enables a GeometryBufferRender and associates it with the scene
  27774. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27775. * @returns the GeometryBufferRenderer
  27776. */
  27777. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27778. if (ratio === void 0) { ratio = 1; }
  27779. if (this._geometryBufferRenderer) {
  27780. return this._geometryBufferRenderer;
  27781. }
  27782. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27783. if (!this._geometryBufferRenderer.isSupported) {
  27784. this._geometryBufferRenderer = null;
  27785. }
  27786. return this._geometryBufferRenderer;
  27787. };
  27788. /**
  27789. * Disables the GeometryBufferRender associated with the scene
  27790. */
  27791. Scene.prototype.disableGeometryBufferRenderer = function () {
  27792. if (!this._geometryBufferRenderer) {
  27793. return;
  27794. }
  27795. this._geometryBufferRenderer.dispose();
  27796. this._geometryBufferRenderer = null;
  27797. };
  27798. /**
  27799. * Freeze all materials
  27800. * A frozen material will not be updatable but should be faster to render
  27801. */
  27802. Scene.prototype.freezeMaterials = function () {
  27803. for (var i = 0; i < this.materials.length; i++) {
  27804. this.materials[i].freeze();
  27805. }
  27806. };
  27807. /**
  27808. * Unfreeze all materials
  27809. * A frozen material will not be updatable but should be faster to render
  27810. */
  27811. Scene.prototype.unfreezeMaterials = function () {
  27812. for (var i = 0; i < this.materials.length; i++) {
  27813. this.materials[i].unfreeze();
  27814. }
  27815. };
  27816. /**
  27817. * Releases all held ressources
  27818. */
  27819. Scene.prototype.dispose = function () {
  27820. this.beforeRender = null;
  27821. this.afterRender = null;
  27822. this.skeletons = [];
  27823. this.morphTargetManagers = [];
  27824. this._transientComponents = [];
  27825. this._isReadyForMeshStage.clear();
  27826. this._beforeEvaluateActiveMeshStage.clear();
  27827. this._evaluateSubMeshStage.clear();
  27828. this._activeMeshStage.clear();
  27829. this._cameraDrawRenderTargetStage.clear();
  27830. this._beforeCameraDrawStage.clear();
  27831. this._beforeRenderingGroupDrawStage.clear();
  27832. this._afterRenderingGroupDrawStage.clear();
  27833. this._afterCameraDrawStage.clear();
  27834. this._beforeCameraUpdateStage.clear();
  27835. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27836. var component = _a[_i];
  27837. component.dispose();
  27838. }
  27839. this.importedMeshesFiles = new Array();
  27840. this.stopAllAnimations();
  27841. this.resetCachedMaterial();
  27842. for (var key in this._depthRenderer) {
  27843. this._depthRenderer[key].dispose();
  27844. }
  27845. // Smart arrays
  27846. if (this.activeCamera) {
  27847. this.activeCamera._activeMeshes.dispose();
  27848. this.activeCamera = null;
  27849. }
  27850. this._activeMeshes.dispose();
  27851. this._renderingManager.dispose();
  27852. this._processedMaterials.dispose();
  27853. this._activeParticleSystems.dispose();
  27854. this._activeSkeletons.dispose();
  27855. this._softwareSkinnedMeshes.dispose();
  27856. this._renderTargets.dispose();
  27857. this._registeredForLateAnimationBindings.dispose();
  27858. this._meshesForIntersections.dispose();
  27859. this._toBeDisposed.dispose();
  27860. // Abort active requests
  27861. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27862. var request = _c[_b];
  27863. request.abort();
  27864. }
  27865. // Debug layer
  27866. if (this._debugLayer) {
  27867. this._debugLayer.hide();
  27868. }
  27869. // Events
  27870. this.onDisposeObservable.notifyObservers(this);
  27871. this.onDisposeObservable.clear();
  27872. this.onBeforeRenderObservable.clear();
  27873. this.onAfterRenderObservable.clear();
  27874. this.onBeforeRenderTargetsRenderObservable.clear();
  27875. this.onAfterRenderTargetsRenderObservable.clear();
  27876. this.onAfterStepObservable.clear();
  27877. this.onBeforeStepObservable.clear();
  27878. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27879. this.onAfterActiveMeshesEvaluationObservable.clear();
  27880. this.onBeforeParticlesRenderingObservable.clear();
  27881. this.onAfterParticlesRenderingObservable.clear();
  27882. this.onBeforeSpritesRenderingObservable.clear();
  27883. this.onAfterSpritesRenderingObservable.clear();
  27884. this.onBeforeDrawPhaseObservable.clear();
  27885. this.onAfterDrawPhaseObservable.clear();
  27886. this.onBeforePhysicsObservable.clear();
  27887. this.onAfterPhysicsObservable.clear();
  27888. this.onBeforeAnimationsObservable.clear();
  27889. this.onAfterAnimationsObservable.clear();
  27890. this.onDataLoadedObservable.clear();
  27891. this.onBeforeRenderingGroupObservable.clear();
  27892. this.onAfterRenderingGroupObservable.clear();
  27893. this.detachControl();
  27894. // Release sounds & sounds tracks
  27895. if (BABYLON.AudioEngine) {
  27896. this.disposeSounds();
  27897. }
  27898. // VR Helper
  27899. if (this.VRHelper) {
  27900. this.VRHelper.dispose();
  27901. }
  27902. // Detach cameras
  27903. var canvas = this._engine.getRenderingCanvas();
  27904. if (canvas) {
  27905. var index;
  27906. for (index = 0; index < this.cameras.length; index++) {
  27907. this.cameras[index].detachControl(canvas);
  27908. }
  27909. }
  27910. // Release animation groups
  27911. while (this.animationGroups.length) {
  27912. this.animationGroups[0].dispose();
  27913. }
  27914. // Release lights
  27915. while (this.lights.length) {
  27916. this.lights[0].dispose();
  27917. }
  27918. // Release meshes
  27919. while (this.meshes.length) {
  27920. this.meshes[0].dispose(true);
  27921. }
  27922. while (this.transformNodes.length) {
  27923. this.removeTransformNode(this.transformNodes[0]);
  27924. }
  27925. // Release cameras
  27926. while (this.cameras.length) {
  27927. this.cameras[0].dispose();
  27928. }
  27929. // Release materials
  27930. if (this.defaultMaterial) {
  27931. this.defaultMaterial.dispose();
  27932. }
  27933. while (this.multiMaterials.length) {
  27934. this.multiMaterials[0].dispose();
  27935. }
  27936. while (this.materials.length) {
  27937. this.materials[0].dispose();
  27938. }
  27939. // Release particles
  27940. while (this.particleSystems.length) {
  27941. this.particleSystems[0].dispose();
  27942. }
  27943. // Release sprites
  27944. while (this.spriteManagers.length) {
  27945. this.spriteManagers[0].dispose();
  27946. }
  27947. // Release postProcesses
  27948. while (this.postProcesses.length) {
  27949. this.postProcesses[0].dispose();
  27950. }
  27951. // Release textures
  27952. while (this.textures.length) {
  27953. this.textures[0].dispose();
  27954. }
  27955. // Release UBO
  27956. this._sceneUbo.dispose();
  27957. if (this._alternateSceneUbo) {
  27958. this._alternateSceneUbo.dispose();
  27959. }
  27960. // Post-processes
  27961. this.postProcessManager.dispose();
  27962. if (this._postProcessRenderPipelineManager) {
  27963. this._postProcessRenderPipelineManager.dispose();
  27964. }
  27965. // Physics
  27966. if (this._physicsEngine) {
  27967. this.disablePhysicsEngine();
  27968. }
  27969. // Remove from engine
  27970. index = this._engine.scenes.indexOf(this);
  27971. if (index > -1) {
  27972. this._engine.scenes.splice(index, 1);
  27973. }
  27974. this._engine.wipeCaches(true);
  27975. this._isDisposed = true;
  27976. };
  27977. Object.defineProperty(Scene.prototype, "isDisposed", {
  27978. /**
  27979. * Gets if the scene is already disposed
  27980. */
  27981. get: function () {
  27982. return this._isDisposed;
  27983. },
  27984. enumerable: true,
  27985. configurable: true
  27986. });
  27987. /**
  27988. * Releases sounds & soundtracks
  27989. */
  27990. Scene.prototype.disposeSounds = function () {
  27991. if (!this._mainSoundTrack) {
  27992. return;
  27993. }
  27994. this.mainSoundTrack.dispose();
  27995. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27996. this.soundTracks[scIndex].dispose();
  27997. }
  27998. };
  27999. /**
  28000. * Call this function to reduce memory footprint of the scene.
  28001. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28002. */
  28003. Scene.prototype.clearCachedVertexData = function () {
  28004. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28005. var mesh = this.meshes[meshIndex];
  28006. var geometry = mesh.geometry;
  28007. if (geometry) {
  28008. geometry._indices = [];
  28009. for (var vbName in geometry._vertexBuffers) {
  28010. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28011. continue;
  28012. }
  28013. geometry._vertexBuffers[vbName]._buffer._data = null;
  28014. }
  28015. }
  28016. }
  28017. };
  28018. /**
  28019. * This function will remove the local cached buffer data from texture.
  28020. * It will save memory but will prevent the texture from being rebuilt
  28021. */
  28022. Scene.prototype.cleanCachedTextureBuffer = function () {
  28023. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28024. var baseTexture = _a[_i];
  28025. var buffer = baseTexture._buffer;
  28026. if (buffer) {
  28027. baseTexture._buffer = null;
  28028. }
  28029. }
  28030. };
  28031. // Octrees
  28032. /**
  28033. * Get the world extend vectors with an optional filter
  28034. *
  28035. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28036. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28037. */
  28038. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28039. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28040. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28041. filterPredicate = filterPredicate || (function () { return true; });
  28042. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28043. mesh.computeWorldMatrix(true);
  28044. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28045. return;
  28046. }
  28047. var boundingInfo = mesh.getBoundingInfo();
  28048. var minBox = boundingInfo.boundingBox.minimumWorld;
  28049. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28050. BABYLON.Tools.CheckExtends(minBox, min, max);
  28051. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28052. });
  28053. return {
  28054. min: min,
  28055. max: max
  28056. };
  28057. };
  28058. /**
  28059. * Creates or updates the octree used to boost selection (picking)
  28060. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28061. * @param maxCapacity defines the maximum capacity per leaf
  28062. * @param maxDepth defines the maximum depth of the octree
  28063. * @returns an octree of AbstractMesh
  28064. */
  28065. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28066. if (maxCapacity === void 0) { maxCapacity = 64; }
  28067. if (maxDepth === void 0) { maxDepth = 2; }
  28068. if (!this._selectionOctree) {
  28069. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28070. }
  28071. var worldExtends = this.getWorldExtends();
  28072. // Update octree
  28073. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28074. return this._selectionOctree;
  28075. };
  28076. // Picking
  28077. /**
  28078. * Creates a ray that can be used to pick in the scene
  28079. * @param x defines the x coordinate of the origin (on-screen)
  28080. * @param y defines the y coordinate of the origin (on-screen)
  28081. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28082. * @param camera defines the camera to use for the picking
  28083. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28084. * @returns a Ray
  28085. */
  28086. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28087. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28088. var result = BABYLON.Ray.Zero();
  28089. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28090. return result;
  28091. };
  28092. /**
  28093. * Creates a ray that can be used to pick in the scene
  28094. * @param x defines the x coordinate of the origin (on-screen)
  28095. * @param y defines the y coordinate of the origin (on-screen)
  28096. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28097. * @param result defines the ray where to store the picking ray
  28098. * @param camera defines the camera to use for the picking
  28099. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28100. * @returns the current scene
  28101. */
  28102. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28103. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28104. var engine = this._engine;
  28105. if (!camera) {
  28106. if (!this.activeCamera)
  28107. throw new Error("Active camera not set");
  28108. camera = this.activeCamera;
  28109. }
  28110. var cameraViewport = camera.viewport;
  28111. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28112. // Moving coordinates to local viewport world
  28113. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28114. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28115. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28116. return this;
  28117. };
  28118. /**
  28119. * Creates a ray that can be used to pick in the scene
  28120. * @param x defines the x coordinate of the origin (on-screen)
  28121. * @param y defines the y coordinate of the origin (on-screen)
  28122. * @param camera defines the camera to use for the picking
  28123. * @returns a Ray
  28124. */
  28125. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28126. var result = BABYLON.Ray.Zero();
  28127. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28128. return result;
  28129. };
  28130. /**
  28131. * Creates a ray that can be used to pick in the scene
  28132. * @param x defines the x coordinate of the origin (on-screen)
  28133. * @param y defines the y coordinate of the origin (on-screen)
  28134. * @param result defines the ray where to store the picking ray
  28135. * @param camera defines the camera to use for the picking
  28136. * @returns the current scene
  28137. */
  28138. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28139. if (!BABYLON.PickingInfo) {
  28140. return this;
  28141. }
  28142. var engine = this._engine;
  28143. if (!camera) {
  28144. if (!this.activeCamera)
  28145. throw new Error("Active camera not set");
  28146. camera = this.activeCamera;
  28147. }
  28148. var cameraViewport = camera.viewport;
  28149. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28150. var identity = BABYLON.Matrix.Identity();
  28151. // Moving coordinates to local viewport world
  28152. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28153. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28154. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28155. return this;
  28156. };
  28157. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28158. if (!BABYLON.PickingInfo) {
  28159. return null;
  28160. }
  28161. var pickingInfo = null;
  28162. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28163. var mesh = this.meshes[meshIndex];
  28164. if (predicate) {
  28165. if (!predicate(mesh)) {
  28166. continue;
  28167. }
  28168. }
  28169. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28170. continue;
  28171. }
  28172. var world = mesh.getWorldMatrix();
  28173. var ray = rayFunction(world);
  28174. var result = mesh.intersects(ray, fastCheck);
  28175. if (!result || !result.hit)
  28176. continue;
  28177. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28178. continue;
  28179. pickingInfo = result;
  28180. if (fastCheck) {
  28181. break;
  28182. }
  28183. }
  28184. return pickingInfo || new BABYLON.PickingInfo();
  28185. };
  28186. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28187. if (!BABYLON.PickingInfo) {
  28188. return null;
  28189. }
  28190. var pickingInfos = new Array();
  28191. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28192. var mesh = this.meshes[meshIndex];
  28193. if (predicate) {
  28194. if (!predicate(mesh)) {
  28195. continue;
  28196. }
  28197. }
  28198. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28199. continue;
  28200. }
  28201. var world = mesh.getWorldMatrix();
  28202. var ray = rayFunction(world);
  28203. var result = mesh.intersects(ray, false);
  28204. if (!result || !result.hit)
  28205. continue;
  28206. pickingInfos.push(result);
  28207. }
  28208. return pickingInfos;
  28209. };
  28210. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28211. if (!BABYLON.PickingInfo) {
  28212. return null;
  28213. }
  28214. var pickingInfo = null;
  28215. if (!camera) {
  28216. if (!this.activeCamera) {
  28217. return null;
  28218. }
  28219. camera = this.activeCamera;
  28220. }
  28221. if (this.spriteManagers.length > 0) {
  28222. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28223. var spriteManager = this.spriteManagers[spriteIndex];
  28224. if (!spriteManager.isPickable) {
  28225. continue;
  28226. }
  28227. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28228. if (!result || !result.hit)
  28229. continue;
  28230. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28231. continue;
  28232. pickingInfo = result;
  28233. if (fastCheck) {
  28234. break;
  28235. }
  28236. }
  28237. }
  28238. return pickingInfo || new BABYLON.PickingInfo();
  28239. };
  28240. /** Launch a ray to try to pick a mesh in the scene
  28241. * @param x position on screen
  28242. * @param y position on screen
  28243. * @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
  28244. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28245. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28246. * @returns a PickingInfo
  28247. */
  28248. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28249. var _this = this;
  28250. if (!BABYLON.PickingInfo) {
  28251. return null;
  28252. }
  28253. var result = this._internalPick(function (world) {
  28254. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28255. return _this._tempPickingRay;
  28256. }, predicate, fastCheck);
  28257. if (result) {
  28258. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28259. }
  28260. return result;
  28261. };
  28262. /** Launch a ray to try to pick a sprite in the scene
  28263. * @param x position on screen
  28264. * @param y position on screen
  28265. * @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
  28266. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28267. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28268. * @returns a PickingInfo
  28269. */
  28270. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28271. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28272. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28273. };
  28274. /** Use the given ray to pick a mesh in the scene
  28275. * @param ray The ray to use to pick meshes
  28276. * @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
  28277. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28278. * @returns a PickingInfo
  28279. */
  28280. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28281. var _this = this;
  28282. var result = this._internalPick(function (world) {
  28283. if (!_this._pickWithRayInverseMatrix) {
  28284. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28285. }
  28286. world.invertToRef(_this._pickWithRayInverseMatrix);
  28287. if (!_this._cachedRayForTransform) {
  28288. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28289. }
  28290. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28291. return _this._cachedRayForTransform;
  28292. }, predicate, fastCheck);
  28293. if (result) {
  28294. result.ray = ray;
  28295. }
  28296. return result;
  28297. };
  28298. /**
  28299. * Launch a ray to try to pick a mesh in the scene
  28300. * @param x X position on screen
  28301. * @param y Y position on screen
  28302. * @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
  28303. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28304. * @returns an array of PickingInfo
  28305. */
  28306. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28307. var _this = this;
  28308. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28309. };
  28310. /**
  28311. * Launch a ray to try to pick a mesh in the scene
  28312. * @param ray Ray to use
  28313. * @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
  28314. * @returns an array of PickingInfo
  28315. */
  28316. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28317. var _this = this;
  28318. return this._internalMultiPick(function (world) {
  28319. if (!_this._pickWithRayInverseMatrix) {
  28320. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28321. }
  28322. world.invertToRef(_this._pickWithRayInverseMatrix);
  28323. if (!_this._cachedRayForTransform) {
  28324. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28325. }
  28326. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28327. return _this._cachedRayForTransform;
  28328. }, predicate);
  28329. };
  28330. /**
  28331. * Force the value of meshUnderPointer
  28332. * @param mesh defines the mesh to use
  28333. */
  28334. Scene.prototype.setPointerOverMesh = function (mesh) {
  28335. if (this._pointerOverMesh === mesh) {
  28336. return;
  28337. }
  28338. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28339. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28340. }
  28341. this._pointerOverMesh = mesh;
  28342. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28343. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28344. }
  28345. };
  28346. /**
  28347. * Gets the mesh under the pointer
  28348. * @returns a Mesh or null if no mesh is under the pointer
  28349. */
  28350. Scene.prototype.getPointerOverMesh = function () {
  28351. return this._pointerOverMesh;
  28352. };
  28353. /**
  28354. * Force the sprite under the pointer
  28355. * @param sprite defines the sprite to use
  28356. */
  28357. Scene.prototype.setPointerOverSprite = function (sprite) {
  28358. if (this._pointerOverSprite === sprite) {
  28359. return;
  28360. }
  28361. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28362. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28363. }
  28364. this._pointerOverSprite = sprite;
  28365. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28366. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28367. }
  28368. };
  28369. /**
  28370. * Gets the sprite under the pointer
  28371. * @returns a Sprite or null if no sprite is under the pointer
  28372. */
  28373. Scene.prototype.getPointerOverSprite = function () {
  28374. return this._pointerOverSprite;
  28375. };
  28376. // Physics
  28377. /**
  28378. * Gets the current physics engine
  28379. * @returns a PhysicsEngine or null if none attached
  28380. */
  28381. Scene.prototype.getPhysicsEngine = function () {
  28382. return this._physicsEngine;
  28383. };
  28384. /**
  28385. * Enables physics to the current scene
  28386. * @param gravity defines the scene's gravity for the physics engine
  28387. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28388. * @return a boolean indicating if the physics engine was initialized
  28389. */
  28390. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28391. if (gravity === void 0) { gravity = null; }
  28392. if (this._physicsEngine) {
  28393. return true;
  28394. }
  28395. try {
  28396. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28397. return true;
  28398. }
  28399. catch (e) {
  28400. BABYLON.Tools.Error(e.message);
  28401. return false;
  28402. }
  28403. };
  28404. /**
  28405. * Disables and disposes the physics engine associated with the scene
  28406. */
  28407. Scene.prototype.disablePhysicsEngine = function () {
  28408. if (!this._physicsEngine) {
  28409. return;
  28410. }
  28411. this._physicsEngine.dispose();
  28412. this._physicsEngine = null;
  28413. };
  28414. /**
  28415. * Gets a boolean indicating if there is an active physics engine
  28416. * @returns a boolean indicating if there is an active physics engine
  28417. */
  28418. Scene.prototype.isPhysicsEnabled = function () {
  28419. return this._physicsEngine !== undefined;
  28420. };
  28421. /**
  28422. * Deletes a physics compound impostor
  28423. * @param compound defines the compound to delete
  28424. */
  28425. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28426. var mesh = compound.parts[0].mesh;
  28427. if (mesh.physicsImpostor) {
  28428. mesh.physicsImpostor.dispose( /*true*/);
  28429. mesh.physicsImpostor = null;
  28430. }
  28431. };
  28432. // Misc.
  28433. /** @hidden */
  28434. Scene.prototype._rebuildGeometries = function () {
  28435. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28436. var geometry = _a[_i];
  28437. geometry._rebuild();
  28438. }
  28439. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28440. var mesh = _c[_b];
  28441. mesh._rebuild();
  28442. }
  28443. if (this.postProcessManager) {
  28444. this.postProcessManager._rebuild();
  28445. }
  28446. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28447. var component = _e[_d];
  28448. component.rebuild();
  28449. }
  28450. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28451. var system = _g[_f];
  28452. system.rebuild();
  28453. }
  28454. if (this._postProcessRenderPipelineManager) {
  28455. this._postProcessRenderPipelineManager._rebuild();
  28456. }
  28457. };
  28458. /** @hidden */
  28459. Scene.prototype._rebuildTextures = function () {
  28460. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28461. var texture = _a[_i];
  28462. texture._rebuild();
  28463. }
  28464. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28465. };
  28466. /**
  28467. * Creates a default light for the scene.
  28468. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28469. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28470. */
  28471. Scene.prototype.createDefaultLight = function (replace) {
  28472. if (replace === void 0) { replace = false; }
  28473. // Dispose existing light in replace mode.
  28474. if (replace) {
  28475. if (this.lights) {
  28476. for (var i = 0; i < this.lights.length; i++) {
  28477. this.lights[i].dispose();
  28478. }
  28479. }
  28480. }
  28481. // Light
  28482. if (this.lights.length === 0) {
  28483. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28484. }
  28485. };
  28486. /**
  28487. * Creates a default camera for the scene.
  28488. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28489. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28490. * @param replace has default false, when true replaces the active camera in the scene
  28491. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28492. */
  28493. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28494. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28495. if (replace === void 0) { replace = false; }
  28496. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28497. // Dispose existing camera in replace mode.
  28498. if (replace) {
  28499. if (this.activeCamera) {
  28500. this.activeCamera.dispose();
  28501. this.activeCamera = null;
  28502. }
  28503. }
  28504. // Camera
  28505. if (!this.activeCamera) {
  28506. var worldExtends = this.getWorldExtends();
  28507. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28508. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28509. var camera;
  28510. var radius = worldSize.length() * 1.5;
  28511. // empty scene scenario!
  28512. if (!isFinite(radius)) {
  28513. radius = 1;
  28514. worldCenter.copyFromFloats(0, 0, 0);
  28515. }
  28516. if (createArcRotateCamera) {
  28517. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28518. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28519. arcRotateCamera.wheelPrecision = 100 / radius;
  28520. camera = arcRotateCamera;
  28521. }
  28522. else {
  28523. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28524. freeCamera.setTarget(worldCenter);
  28525. camera = freeCamera;
  28526. }
  28527. camera.minZ = radius * 0.01;
  28528. camera.maxZ = radius * 1000;
  28529. camera.speed = radius * 0.2;
  28530. this.activeCamera = camera;
  28531. var canvas = this.getEngine().getRenderingCanvas();
  28532. if (attachCameraControls && canvas) {
  28533. camera.attachControl(canvas);
  28534. }
  28535. }
  28536. };
  28537. /**
  28538. * Creates a default camera and a default light.
  28539. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28540. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28541. * @param replace has the default false, when true replaces the active camera/light in the scene
  28542. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28543. */
  28544. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28545. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28546. if (replace === void 0) { replace = false; }
  28547. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28548. this.createDefaultLight(replace);
  28549. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28550. };
  28551. /**
  28552. * Creates a new sky box
  28553. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28554. * @param environmentTexture defines the texture to use as environment texture
  28555. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28556. * @param scale defines the overall scale of the skybox
  28557. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28558. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28559. * @returns a new mesh holding the sky box
  28560. */
  28561. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28562. if (pbr === void 0) { pbr = false; }
  28563. if (scale === void 0) { scale = 1000; }
  28564. if (blur === void 0) { blur = 0; }
  28565. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28566. if (!environmentTexture) {
  28567. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28568. return null;
  28569. }
  28570. if (setGlobalEnvTexture) {
  28571. if (environmentTexture) {
  28572. this.environmentTexture = environmentTexture;
  28573. }
  28574. }
  28575. // Skybox
  28576. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28577. if (pbr) {
  28578. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28579. hdrSkyboxMaterial.backFaceCulling = false;
  28580. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28581. if (hdrSkyboxMaterial.reflectionTexture) {
  28582. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28583. }
  28584. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28585. hdrSkyboxMaterial.disableLighting = true;
  28586. hdrSkyboxMaterial.twoSidedLighting = true;
  28587. hdrSkybox.infiniteDistance = true;
  28588. hdrSkybox.material = hdrSkyboxMaterial;
  28589. }
  28590. else {
  28591. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28592. skyboxMaterial.backFaceCulling = false;
  28593. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28594. if (skyboxMaterial.reflectionTexture) {
  28595. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28596. }
  28597. skyboxMaterial.disableLighting = true;
  28598. hdrSkybox.infiniteDistance = true;
  28599. hdrSkybox.material = skyboxMaterial;
  28600. }
  28601. return hdrSkybox;
  28602. };
  28603. /**
  28604. * Creates a new environment
  28605. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28606. * @param options defines the options you can use to configure the environment
  28607. * @returns the new EnvironmentHelper
  28608. */
  28609. Scene.prototype.createDefaultEnvironment = function (options) {
  28610. if (BABYLON.EnvironmentHelper) {
  28611. return new BABYLON.EnvironmentHelper(options, this);
  28612. }
  28613. return null;
  28614. };
  28615. /**
  28616. * Creates a new VREXperienceHelper
  28617. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28618. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28619. * @returns a new VREXperienceHelper
  28620. */
  28621. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28622. if (webVROptions === void 0) { webVROptions = {}; }
  28623. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28624. };
  28625. // Tags
  28626. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28627. if (tagsQuery === undefined) {
  28628. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28629. return list;
  28630. }
  28631. var listByTags = [];
  28632. forEach = forEach || (function (item) { return; });
  28633. for (var i in list) {
  28634. var item = list[i];
  28635. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28636. listByTags.push(item);
  28637. forEach(item);
  28638. }
  28639. }
  28640. return listByTags;
  28641. };
  28642. /**
  28643. * Get a list of meshes by tags
  28644. * @param tagsQuery defines the tags query to use
  28645. * @param forEach defines a predicate used to filter results
  28646. * @returns an array of Mesh
  28647. */
  28648. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28649. return this._getByTags(this.meshes, tagsQuery, forEach);
  28650. };
  28651. /**
  28652. * Get a list of cameras by tags
  28653. * @param tagsQuery defines the tags query to use
  28654. * @param forEach defines a predicate used to filter results
  28655. * @returns an array of Camera
  28656. */
  28657. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28658. return this._getByTags(this.cameras, tagsQuery, forEach);
  28659. };
  28660. /**
  28661. * Get a list of lights by tags
  28662. * @param tagsQuery defines the tags query to use
  28663. * @param forEach defines a predicate used to filter results
  28664. * @returns an array of Light
  28665. */
  28666. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28667. return this._getByTags(this.lights, tagsQuery, forEach);
  28668. };
  28669. /**
  28670. * Get a list of materials by tags
  28671. * @param tagsQuery defines the tags query to use
  28672. * @param forEach defines a predicate used to filter results
  28673. * @returns an array of Material
  28674. */
  28675. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28676. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28677. };
  28678. /**
  28679. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28680. * This allowed control for front to back rendering or reversly depending of the special needs.
  28681. *
  28682. * @param renderingGroupId The rendering group id corresponding to its index
  28683. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28684. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28685. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28686. */
  28687. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28688. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28689. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28690. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28691. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28692. };
  28693. /**
  28694. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28695. *
  28696. * @param renderingGroupId The rendering group id corresponding to its index
  28697. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28698. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28699. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28700. */
  28701. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28702. if (depth === void 0) { depth = true; }
  28703. if (stencil === void 0) { stencil = true; }
  28704. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28705. };
  28706. /**
  28707. * Gets the current auto clear configuration for one rendering group of the rendering
  28708. * manager.
  28709. * @param index the rendering group index to get the information for
  28710. * @returns The auto clear setup for the requested rendering group
  28711. */
  28712. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28713. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28714. };
  28715. /**
  28716. * Will flag all materials as dirty to trigger new shader compilation
  28717. * @param flag defines the flag used to specify which material part must be marked as dirty
  28718. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28719. */
  28720. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28721. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28722. var material = _a[_i];
  28723. if (predicate && !predicate(material)) {
  28724. continue;
  28725. }
  28726. material.markAsDirty(flag);
  28727. }
  28728. };
  28729. /** @hidden */
  28730. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28731. var _this = this;
  28732. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28733. this._activeRequests.push(request);
  28734. request.onCompleteObservable.add(function (request) {
  28735. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28736. });
  28737. return request;
  28738. };
  28739. /** @hidden */
  28740. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28741. var _this = this;
  28742. return new Promise(function (resolve, reject) {
  28743. _this._loadFile(url, function (data) {
  28744. resolve(data);
  28745. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28746. reject(exception);
  28747. });
  28748. });
  28749. };
  28750. // Statics
  28751. Scene._FOGMODE_NONE = 0;
  28752. Scene._FOGMODE_EXP = 1;
  28753. Scene._FOGMODE_EXP2 = 2;
  28754. Scene._FOGMODE_LINEAR = 3;
  28755. Scene._uniqueIdCounter = 0;
  28756. /**
  28757. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28758. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28759. */
  28760. Scene.MinDeltaTime = 1.0;
  28761. /**
  28762. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28763. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28764. */
  28765. Scene.MaxDeltaTime = 1000.0;
  28766. /** The distance in pixel that you have to move to prevent some events */
  28767. Scene.DragMovementThreshold = 10; // in pixels
  28768. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28769. Scene.LongPressDelay = 500; // in milliseconds
  28770. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28771. Scene.DoubleClickDelay = 300; // in milliseconds
  28772. /** If you need to check double click without raising a single click at first click, enable this flag */
  28773. Scene.ExclusiveDoubleClickMode = false;
  28774. return Scene;
  28775. }(BABYLON.AbstractScene));
  28776. BABYLON.Scene = Scene;
  28777. })(BABYLON || (BABYLON = {}));
  28778. //# sourceMappingURL=babylon.scene.js.map
  28779. var BABYLON;
  28780. (function (BABYLON) {
  28781. /**
  28782. * Set of assets to keep when moving a scene into an asset container.
  28783. */
  28784. var KeepAssets = /** @class */ (function (_super) {
  28785. __extends(KeepAssets, _super);
  28786. function KeepAssets() {
  28787. return _super !== null && _super.apply(this, arguments) || this;
  28788. }
  28789. return KeepAssets;
  28790. }(BABYLON.AbstractScene));
  28791. BABYLON.KeepAssets = KeepAssets;
  28792. /**
  28793. * Container with a set of assets that can be added or removed from a scene.
  28794. */
  28795. var AssetContainer = /** @class */ (function (_super) {
  28796. __extends(AssetContainer, _super);
  28797. /**
  28798. * Instantiates an AssetContainer.
  28799. * @param scene The scene the AssetContainer belongs to.
  28800. */
  28801. function AssetContainer(scene) {
  28802. var _this = _super.call(this) || this;
  28803. _this.scene = scene;
  28804. return _this;
  28805. }
  28806. /**
  28807. * Adds all the assets from the container to the scene.
  28808. */
  28809. AssetContainer.prototype.addAllToScene = function () {
  28810. var _this = this;
  28811. this.cameras.forEach(function (o) {
  28812. _this.scene.addCamera(o);
  28813. });
  28814. this.lights.forEach(function (o) {
  28815. _this.scene.addLight(o);
  28816. });
  28817. this.meshes.forEach(function (o) {
  28818. _this.scene.addMesh(o);
  28819. });
  28820. this.skeletons.forEach(function (o) {
  28821. _this.scene.addSkeleton(o);
  28822. });
  28823. this.animations.forEach(function (o) {
  28824. _this.scene.addAnimation(o);
  28825. });
  28826. this.animationGroups.forEach(function (o) {
  28827. _this.scene.addAnimationGroup(o);
  28828. });
  28829. this.multiMaterials.forEach(function (o) {
  28830. _this.scene.addMultiMaterial(o);
  28831. });
  28832. this.materials.forEach(function (o) {
  28833. _this.scene.addMaterial(o);
  28834. });
  28835. this.morphTargetManagers.forEach(function (o) {
  28836. _this.scene.addMorphTargetManager(o);
  28837. });
  28838. this.geometries.forEach(function (o) {
  28839. _this.scene.addGeometry(o);
  28840. });
  28841. this.transformNodes.forEach(function (o) {
  28842. _this.scene.addTransformNode(o);
  28843. });
  28844. this.actionManagers.forEach(function (o) {
  28845. _this.scene.addActionManager(o);
  28846. });
  28847. this.sounds.forEach(function (o) {
  28848. o.play();
  28849. o.autoplay = true;
  28850. _this.scene.mainSoundTrack.AddSound(o);
  28851. });
  28852. this.textures.forEach(function (o) {
  28853. _this.scene.addTexture(o);
  28854. });
  28855. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28856. var component = _a[_i];
  28857. component.addFromContainer(this.scene);
  28858. }
  28859. };
  28860. /**
  28861. * Removes all the assets in the container from the scene
  28862. */
  28863. AssetContainer.prototype.removeAllFromScene = function () {
  28864. var _this = this;
  28865. this.cameras.forEach(function (o) {
  28866. _this.scene.removeCamera(o);
  28867. });
  28868. this.lights.forEach(function (o) {
  28869. _this.scene.removeLight(o);
  28870. });
  28871. this.meshes.forEach(function (o) {
  28872. _this.scene.removeMesh(o);
  28873. });
  28874. this.skeletons.forEach(function (o) {
  28875. _this.scene.removeSkeleton(o);
  28876. });
  28877. this.animations.forEach(function (o) {
  28878. _this.scene.removeAnimation(o);
  28879. });
  28880. this.animationGroups.forEach(function (o) {
  28881. _this.scene.removeAnimationGroup(o);
  28882. });
  28883. this.multiMaterials.forEach(function (o) {
  28884. _this.scene.removeMultiMaterial(o);
  28885. });
  28886. this.materials.forEach(function (o) {
  28887. _this.scene.removeMaterial(o);
  28888. });
  28889. this.morphTargetManagers.forEach(function (o) {
  28890. _this.scene.removeMorphTargetManager(o);
  28891. });
  28892. this.geometries.forEach(function (o) {
  28893. _this.scene.removeGeometry(o);
  28894. });
  28895. this.transformNodes.forEach(function (o) {
  28896. _this.scene.removeTransformNode(o);
  28897. });
  28898. this.actionManagers.forEach(function (o) {
  28899. _this.scene.removeActionManager(o);
  28900. });
  28901. this.sounds.forEach(function (o) {
  28902. o.stop();
  28903. o.autoplay = false;
  28904. _this.scene.mainSoundTrack.RemoveSound(o);
  28905. });
  28906. this.textures.forEach(function (o) {
  28907. _this.scene.removeTexture(o);
  28908. });
  28909. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28910. var component = _a[_i];
  28911. component.removeFromContainer(this.scene);
  28912. }
  28913. };
  28914. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28915. if (!sourceAssets) {
  28916. return;
  28917. }
  28918. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28919. var asset = sourceAssets_1[_i];
  28920. var move = true;
  28921. if (keepAssets) {
  28922. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28923. var keepAsset = keepAssets_1[_a];
  28924. if (asset === keepAsset) {
  28925. move = false;
  28926. break;
  28927. }
  28928. }
  28929. }
  28930. if (move) {
  28931. targetAssets.push(asset);
  28932. }
  28933. }
  28934. };
  28935. /**
  28936. * Removes all the assets contained in the scene and adds them to the container.
  28937. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28938. */
  28939. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28940. if (keepAssets === undefined) {
  28941. keepAssets = new KeepAssets();
  28942. }
  28943. for (var key in this) {
  28944. if (this.hasOwnProperty(key)) {
  28945. this[key] = this[key] || [];
  28946. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28947. }
  28948. }
  28949. this.removeAllFromScene();
  28950. };
  28951. /**
  28952. * 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.
  28953. * @returns the root mesh
  28954. */
  28955. AssetContainer.prototype.createRootMesh = function () {
  28956. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28957. this.meshes.forEach(function (m) {
  28958. if (!m.parent) {
  28959. rootMesh.addChild(m);
  28960. }
  28961. });
  28962. this.meshes.unshift(rootMesh);
  28963. return rootMesh;
  28964. };
  28965. return AssetContainer;
  28966. }(BABYLON.AbstractScene));
  28967. BABYLON.AssetContainer = AssetContainer;
  28968. })(BABYLON || (BABYLON = {}));
  28969. //# sourceMappingURL=babylon.assetContainer.js.map
  28970. var BABYLON;
  28971. (function (BABYLON) {
  28972. var Buffer = /** @class */ (function () {
  28973. /**
  28974. * Constructor
  28975. * @param engine the engine
  28976. * @param data the data to use for this buffer
  28977. * @param updatable whether the data is updatable
  28978. * @param stride the stride (optional)
  28979. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28980. * @param instanced whether the buffer is instanced (optional)
  28981. * @param useBytes set to true if the stride in in bytes (optional)
  28982. */
  28983. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28984. if (stride === void 0) { stride = 0; }
  28985. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28986. if (instanced === void 0) { instanced = false; }
  28987. if (useBytes === void 0) { useBytes = false; }
  28988. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28989. this._engine = engine.getScene().getEngine();
  28990. }
  28991. else {
  28992. this._engine = engine;
  28993. }
  28994. this._updatable = updatable;
  28995. this._instanced = instanced;
  28996. this._data = data;
  28997. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28998. if (!postponeInternalCreation) { // by default
  28999. this.create();
  29000. }
  29001. }
  29002. /**
  29003. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29004. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29005. * @param offset defines offset in the buffer (0 by default)
  29006. * @param size defines the size in floats of attributes (position is 3 for instance)
  29007. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29008. * @param instanced defines if the vertex buffer contains indexed data
  29009. * @param useBytes defines if the offset and stride are in bytes
  29010. * @returns the new vertex buffer
  29011. */
  29012. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29013. if (useBytes === void 0) { useBytes = false; }
  29014. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29015. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29016. // a lot of these parameters are ignored as they are overriden by the buffer
  29017. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29018. };
  29019. // Properties
  29020. Buffer.prototype.isUpdatable = function () {
  29021. return this._updatable;
  29022. };
  29023. Buffer.prototype.getData = function () {
  29024. return this._data;
  29025. };
  29026. Buffer.prototype.getBuffer = function () {
  29027. return this._buffer;
  29028. };
  29029. /**
  29030. * Gets the stride in float32 units (i.e. byte stride / 4).
  29031. * May not be an integer if the byte stride is not divisible by 4.
  29032. * DEPRECATED. Use byteStride instead.
  29033. * @returns the stride in float32 units
  29034. */
  29035. Buffer.prototype.getStrideSize = function () {
  29036. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29037. };
  29038. // Methods
  29039. Buffer.prototype.create = function (data) {
  29040. if (data === void 0) { data = null; }
  29041. if (!data && this._buffer) {
  29042. return; // nothing to do
  29043. }
  29044. data = data || this._data;
  29045. if (!data) {
  29046. return;
  29047. }
  29048. if (!this._buffer) { // create buffer
  29049. if (this._updatable) {
  29050. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29051. this._data = data;
  29052. }
  29053. else {
  29054. this._buffer = this._engine.createVertexBuffer(data);
  29055. }
  29056. }
  29057. else if (this._updatable) { // update buffer
  29058. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29059. this._data = data;
  29060. }
  29061. };
  29062. Buffer.prototype._rebuild = function () {
  29063. this._buffer = null;
  29064. this.create(this._data);
  29065. };
  29066. Buffer.prototype.update = function (data) {
  29067. this.create(data);
  29068. };
  29069. /**
  29070. * Updates the data directly.
  29071. * @param data the new data
  29072. * @param offset the new offset
  29073. * @param vertexCount the vertex count (optional)
  29074. * @param useBytes set to true if the offset is in bytes
  29075. */
  29076. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29077. if (useBytes === void 0) { useBytes = false; }
  29078. if (!this._buffer) {
  29079. return;
  29080. }
  29081. if (this._updatable) { // update buffer
  29082. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29083. this._data = null;
  29084. }
  29085. };
  29086. Buffer.prototype.dispose = function () {
  29087. if (!this._buffer) {
  29088. return;
  29089. }
  29090. if (this._engine._releaseBuffer(this._buffer)) {
  29091. this._buffer = null;
  29092. }
  29093. };
  29094. return Buffer;
  29095. }());
  29096. BABYLON.Buffer = Buffer;
  29097. })(BABYLON || (BABYLON = {}));
  29098. //# sourceMappingURL=babylon.buffer.js.map
  29099. var BABYLON;
  29100. (function (BABYLON) {
  29101. var VertexBuffer = /** @class */ (function () {
  29102. /**
  29103. * Constructor
  29104. * @param engine the engine
  29105. * @param data the data to use for this vertex buffer
  29106. * @param kind the vertex buffer kind
  29107. * @param updatable whether the data is updatable
  29108. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29109. * @param stride the stride (optional)
  29110. * @param instanced whether the buffer is instanced (optional)
  29111. * @param offset the offset of the data (optional)
  29112. * @param size the number of components (optional)
  29113. * @param type the type of the component (optional)
  29114. * @param normalized whether the data contains normalized data (optional)
  29115. * @param useBytes set to true if stride and offset are in bytes (optional)
  29116. */
  29117. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29118. if (normalized === void 0) { normalized = false; }
  29119. if (useBytes === void 0) { useBytes = false; }
  29120. if (data instanceof BABYLON.Buffer) {
  29121. this._buffer = data;
  29122. this._ownsBuffer = false;
  29123. }
  29124. else {
  29125. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29126. this._ownsBuffer = true;
  29127. }
  29128. this._kind = kind;
  29129. if (type == undefined) {
  29130. var data_1 = this.getData();
  29131. this.type = VertexBuffer.FLOAT;
  29132. if (data_1 instanceof Int8Array)
  29133. this.type = VertexBuffer.BYTE;
  29134. else if (data_1 instanceof Uint8Array)
  29135. this.type = VertexBuffer.UNSIGNED_BYTE;
  29136. else if (data_1 instanceof Int16Array)
  29137. this.type = VertexBuffer.SHORT;
  29138. else if (data_1 instanceof Uint16Array)
  29139. this.type = VertexBuffer.UNSIGNED_SHORT;
  29140. else if (data_1 instanceof Int32Array)
  29141. this.type = VertexBuffer.INT;
  29142. else if (data_1 instanceof Uint32Array)
  29143. this.type = VertexBuffer.UNSIGNED_INT;
  29144. }
  29145. else {
  29146. this.type = type;
  29147. }
  29148. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29149. if (useBytes) {
  29150. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29151. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29152. this.byteOffset = offset || 0;
  29153. }
  29154. else {
  29155. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29156. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29157. this.byteOffset = (offset || 0) * typeByteLength;
  29158. }
  29159. this.normalized = normalized;
  29160. this._instanced = instanced !== undefined ? instanced : false;
  29161. this._instanceDivisor = instanced ? 1 : 0;
  29162. }
  29163. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29164. /**
  29165. * Gets or sets the instance divisor when in instanced mode
  29166. */
  29167. get: function () {
  29168. return this._instanceDivisor;
  29169. },
  29170. set: function (value) {
  29171. this._instanceDivisor = value;
  29172. if (value == 0) {
  29173. this._instanced = false;
  29174. }
  29175. else {
  29176. this._instanced = true;
  29177. }
  29178. },
  29179. enumerable: true,
  29180. configurable: true
  29181. });
  29182. VertexBuffer.prototype._rebuild = function () {
  29183. if (!this._buffer) {
  29184. return;
  29185. }
  29186. this._buffer._rebuild();
  29187. };
  29188. /**
  29189. * Returns the kind of the VertexBuffer (string).
  29190. */
  29191. VertexBuffer.prototype.getKind = function () {
  29192. return this._kind;
  29193. };
  29194. // Properties
  29195. /**
  29196. * Boolean : is the VertexBuffer updatable ?
  29197. */
  29198. VertexBuffer.prototype.isUpdatable = function () {
  29199. return this._buffer.isUpdatable();
  29200. };
  29201. /**
  29202. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29203. */
  29204. VertexBuffer.prototype.getData = function () {
  29205. return this._buffer.getData();
  29206. };
  29207. /**
  29208. * Returns the WebGLBuffer associated to the VertexBuffer.
  29209. */
  29210. VertexBuffer.prototype.getBuffer = function () {
  29211. return this._buffer.getBuffer();
  29212. };
  29213. /**
  29214. * Returns the stride as a multiple of the type byte length.
  29215. * DEPRECATED. Use byteStride instead.
  29216. */
  29217. VertexBuffer.prototype.getStrideSize = function () {
  29218. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29219. };
  29220. /**
  29221. * Returns the offset as a multiple of the type byte length.
  29222. * DEPRECATED. Use byteOffset instead.
  29223. */
  29224. VertexBuffer.prototype.getOffset = function () {
  29225. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29226. };
  29227. /**
  29228. * Returns the number of components per vertex attribute (integer).
  29229. */
  29230. VertexBuffer.prototype.getSize = function () {
  29231. return this._size;
  29232. };
  29233. /**
  29234. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29235. */
  29236. VertexBuffer.prototype.getIsInstanced = function () {
  29237. return this._instanced;
  29238. };
  29239. /**
  29240. * Returns the instancing divisor, zero for non-instanced (integer).
  29241. */
  29242. VertexBuffer.prototype.getInstanceDivisor = function () {
  29243. return this._instanceDivisor;
  29244. };
  29245. // Methods
  29246. /**
  29247. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29248. * Returns the created WebGLBuffer.
  29249. */
  29250. VertexBuffer.prototype.create = function (data) {
  29251. return this._buffer.create(data);
  29252. };
  29253. /**
  29254. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29255. * This function will create a new buffer if the current one is not updatable
  29256. * Returns the updated WebGLBuffer.
  29257. */
  29258. VertexBuffer.prototype.update = function (data) {
  29259. return this._buffer.update(data);
  29260. };
  29261. /**
  29262. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29263. * Returns the directly updated WebGLBuffer.
  29264. * @param data the new data
  29265. * @param offset the new offset
  29266. * @param useBytes set to true if the offset is in bytes
  29267. */
  29268. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29269. if (useBytes === void 0) { useBytes = false; }
  29270. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29271. };
  29272. /**
  29273. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29274. */
  29275. VertexBuffer.prototype.dispose = function () {
  29276. if (this._ownsBuffer) {
  29277. this._buffer.dispose();
  29278. }
  29279. };
  29280. /**
  29281. * Enumerates each value of this vertex buffer as numbers.
  29282. * @param count the number of values to enumerate
  29283. * @param callback the callback function called for each value
  29284. */
  29285. VertexBuffer.prototype.forEach = function (count, callback) {
  29286. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29287. };
  29288. Object.defineProperty(VertexBuffer, "PositionKind", {
  29289. get: function () {
  29290. return VertexBuffer._PositionKind;
  29291. },
  29292. enumerable: true,
  29293. configurable: true
  29294. });
  29295. Object.defineProperty(VertexBuffer, "NormalKind", {
  29296. get: function () {
  29297. return VertexBuffer._NormalKind;
  29298. },
  29299. enumerable: true,
  29300. configurable: true
  29301. });
  29302. Object.defineProperty(VertexBuffer, "TangentKind", {
  29303. get: function () {
  29304. return VertexBuffer._TangentKind;
  29305. },
  29306. enumerable: true,
  29307. configurable: true
  29308. });
  29309. Object.defineProperty(VertexBuffer, "UVKind", {
  29310. get: function () {
  29311. return VertexBuffer._UVKind;
  29312. },
  29313. enumerable: true,
  29314. configurable: true
  29315. });
  29316. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29317. get: function () {
  29318. return VertexBuffer._UV2Kind;
  29319. },
  29320. enumerable: true,
  29321. configurable: true
  29322. });
  29323. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29324. get: function () {
  29325. return VertexBuffer._UV3Kind;
  29326. },
  29327. enumerable: true,
  29328. configurable: true
  29329. });
  29330. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29331. get: function () {
  29332. return VertexBuffer._UV4Kind;
  29333. },
  29334. enumerable: true,
  29335. configurable: true
  29336. });
  29337. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29338. get: function () {
  29339. return VertexBuffer._UV5Kind;
  29340. },
  29341. enumerable: true,
  29342. configurable: true
  29343. });
  29344. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29345. get: function () {
  29346. return VertexBuffer._UV6Kind;
  29347. },
  29348. enumerable: true,
  29349. configurable: true
  29350. });
  29351. Object.defineProperty(VertexBuffer, "ColorKind", {
  29352. get: function () {
  29353. return VertexBuffer._ColorKind;
  29354. },
  29355. enumerable: true,
  29356. configurable: true
  29357. });
  29358. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29359. get: function () {
  29360. return VertexBuffer._MatricesIndicesKind;
  29361. },
  29362. enumerable: true,
  29363. configurable: true
  29364. });
  29365. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29366. get: function () {
  29367. return VertexBuffer._MatricesWeightsKind;
  29368. },
  29369. enumerable: true,
  29370. configurable: true
  29371. });
  29372. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29373. get: function () {
  29374. return VertexBuffer._MatricesIndicesExtraKind;
  29375. },
  29376. enumerable: true,
  29377. configurable: true
  29378. });
  29379. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29380. get: function () {
  29381. return VertexBuffer._MatricesWeightsExtraKind;
  29382. },
  29383. enumerable: true,
  29384. configurable: true
  29385. });
  29386. /**
  29387. * Deduces the stride given a kind.
  29388. * @param kind The kind string to deduce
  29389. * @returns The deduced stride
  29390. */
  29391. VertexBuffer.DeduceStride = function (kind) {
  29392. switch (kind) {
  29393. case VertexBuffer.UVKind:
  29394. case VertexBuffer.UV2Kind:
  29395. case VertexBuffer.UV3Kind:
  29396. case VertexBuffer.UV4Kind:
  29397. case VertexBuffer.UV5Kind:
  29398. case VertexBuffer.UV6Kind:
  29399. return 2;
  29400. case VertexBuffer.NormalKind:
  29401. case VertexBuffer.PositionKind:
  29402. return 3;
  29403. case VertexBuffer.ColorKind:
  29404. case VertexBuffer.MatricesIndicesKind:
  29405. case VertexBuffer.MatricesIndicesExtraKind:
  29406. case VertexBuffer.MatricesWeightsKind:
  29407. case VertexBuffer.MatricesWeightsExtraKind:
  29408. case VertexBuffer.TangentKind:
  29409. return 4;
  29410. default:
  29411. throw new Error("Invalid kind '" + kind + "'");
  29412. }
  29413. };
  29414. /**
  29415. * Gets the byte length of the given type.
  29416. * @param type the type
  29417. * @returns the number of bytes
  29418. */
  29419. VertexBuffer.GetTypeByteLength = function (type) {
  29420. switch (type) {
  29421. case VertexBuffer.BYTE:
  29422. case VertexBuffer.UNSIGNED_BYTE:
  29423. return 1;
  29424. case VertexBuffer.SHORT:
  29425. case VertexBuffer.UNSIGNED_SHORT:
  29426. return 2;
  29427. case VertexBuffer.INT:
  29428. case VertexBuffer.FLOAT:
  29429. return 4;
  29430. default:
  29431. throw new Error("Invalid type '" + type + "'");
  29432. }
  29433. };
  29434. /**
  29435. * Enumerates each value of the given parameters as numbers.
  29436. * @param data the data to enumerate
  29437. * @param byteOffset the byte offset of the data
  29438. * @param byteStride the byte stride of the data
  29439. * @param componentCount the number of components per element
  29440. * @param componentType the type of the component
  29441. * @param count the total number of components
  29442. * @param normalized whether the data is normalized
  29443. * @param callback the callback function called for each value
  29444. */
  29445. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29446. if (data instanceof Array) {
  29447. var offset = byteOffset / 4;
  29448. var stride = byteStride / 4;
  29449. for (var index = 0; index < count; index += componentCount) {
  29450. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29451. callback(data[offset + componentIndex], index + componentIndex);
  29452. }
  29453. offset += stride;
  29454. }
  29455. }
  29456. else {
  29457. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29458. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29459. for (var index = 0; index < count; index += componentCount) {
  29460. var componentByteOffset = byteOffset;
  29461. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29462. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29463. callback(value, index + componentIndex);
  29464. componentByteOffset += componentByteLength;
  29465. }
  29466. byteOffset += byteStride;
  29467. }
  29468. }
  29469. };
  29470. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29471. switch (type) {
  29472. case VertexBuffer.BYTE: {
  29473. var value = dataView.getInt8(byteOffset);
  29474. if (normalized) {
  29475. value = Math.max(value / 127, -1);
  29476. }
  29477. return value;
  29478. }
  29479. case VertexBuffer.UNSIGNED_BYTE: {
  29480. var value = dataView.getUint8(byteOffset);
  29481. if (normalized) {
  29482. value = value / 255;
  29483. }
  29484. return value;
  29485. }
  29486. case VertexBuffer.SHORT: {
  29487. var value = dataView.getInt16(byteOffset, true);
  29488. if (normalized) {
  29489. value = Math.max(value / 16383, -1);
  29490. }
  29491. return value;
  29492. }
  29493. case VertexBuffer.UNSIGNED_SHORT: {
  29494. var value = dataView.getUint16(byteOffset, true);
  29495. if (normalized) {
  29496. value = value / 65535;
  29497. }
  29498. return value;
  29499. }
  29500. case VertexBuffer.FLOAT: {
  29501. return dataView.getFloat32(byteOffset, true);
  29502. }
  29503. default: {
  29504. throw new Error("Invalid component type " + type);
  29505. }
  29506. }
  29507. };
  29508. /**
  29509. * The byte type.
  29510. */
  29511. VertexBuffer.BYTE = 5120;
  29512. /**
  29513. * The unsigned byte type.
  29514. */
  29515. VertexBuffer.UNSIGNED_BYTE = 5121;
  29516. /**
  29517. * The short type.
  29518. */
  29519. VertexBuffer.SHORT = 5122;
  29520. /**
  29521. * The unsigned short type.
  29522. */
  29523. VertexBuffer.UNSIGNED_SHORT = 5123;
  29524. /**
  29525. * The integer type.
  29526. */
  29527. VertexBuffer.INT = 5124;
  29528. /**
  29529. * The unsigned integer type.
  29530. */
  29531. VertexBuffer.UNSIGNED_INT = 5125;
  29532. /**
  29533. * The float type.
  29534. */
  29535. VertexBuffer.FLOAT = 5126;
  29536. // Enums
  29537. VertexBuffer._PositionKind = "position";
  29538. VertexBuffer._NormalKind = "normal";
  29539. VertexBuffer._TangentKind = "tangent";
  29540. VertexBuffer._UVKind = "uv";
  29541. VertexBuffer._UV2Kind = "uv2";
  29542. VertexBuffer._UV3Kind = "uv3";
  29543. VertexBuffer._UV4Kind = "uv4";
  29544. VertexBuffer._UV5Kind = "uv5";
  29545. VertexBuffer._UV6Kind = "uv6";
  29546. VertexBuffer._ColorKind = "color";
  29547. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29548. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29549. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29550. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29551. return VertexBuffer;
  29552. }());
  29553. BABYLON.VertexBuffer = VertexBuffer;
  29554. })(BABYLON || (BABYLON = {}));
  29555. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29556. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29557. var BABYLON;
  29558. (function (BABYLON) {
  29559. /**
  29560. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29561. */
  29562. var DummyInternalTextureTracker = /** @class */ (function () {
  29563. function DummyInternalTextureTracker() {
  29564. /**
  29565. * Gets or set the previous tracker in the list
  29566. */
  29567. this.previous = null;
  29568. /**
  29569. * Gets or set the next tracker in the list
  29570. */
  29571. this.next = null;
  29572. }
  29573. return DummyInternalTextureTracker;
  29574. }());
  29575. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29576. })(BABYLON || (BABYLON = {}));
  29577. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29578. var BABYLON;
  29579. (function (BABYLON) {
  29580. /**
  29581. * Class used to store data associated with WebGL texture data for the engine
  29582. * This class should not be used directly
  29583. */
  29584. var InternalTexture = /** @class */ (function () {
  29585. /**
  29586. * Creates a new InternalTexture
  29587. * @param engine defines the engine to use
  29588. * @param dataSource defines the type of data that will be used
  29589. */
  29590. function InternalTexture(engine, dataSource) {
  29591. /**
  29592. * Observable called when the texture is loaded
  29593. */
  29594. this.onLoadedObservable = new BABYLON.Observable();
  29595. /**
  29596. * Gets or set the previous tracker in the list
  29597. */
  29598. this.previous = null;
  29599. /**
  29600. * Gets or set the next tracker in the list
  29601. */
  29602. this.next = null;
  29603. // Private
  29604. /** @hidden */
  29605. this._initialSlot = -1;
  29606. /** @hidden */
  29607. this._designatedSlot = -1;
  29608. /** @hidden */
  29609. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29610. /** @hidden */
  29611. this._comparisonFunction = 0;
  29612. /** @hidden */
  29613. this._sphericalPolynomial = null;
  29614. /** @hidden */
  29615. this._lodGenerationScale = 0;
  29616. /** @hidden */
  29617. this._lodGenerationOffset = 0;
  29618. /** @hidden */
  29619. this._isRGBD = false;
  29620. /** @hidden */
  29621. this._references = 1;
  29622. this._engine = engine;
  29623. this._dataSource = dataSource;
  29624. this._webGLTexture = engine._createTexture();
  29625. }
  29626. /**
  29627. * Gets the Engine the texture belongs to.
  29628. * @returns The babylon engine
  29629. */
  29630. InternalTexture.prototype.getEngine = function () {
  29631. return this._engine;
  29632. };
  29633. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29634. /**
  29635. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29636. */
  29637. get: function () {
  29638. return this._dataSource;
  29639. },
  29640. enumerable: true,
  29641. configurable: true
  29642. });
  29643. /**
  29644. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29645. */
  29646. InternalTexture.prototype.incrementReferences = function () {
  29647. this._references++;
  29648. };
  29649. /**
  29650. * Change the size of the texture (not the size of the content)
  29651. * @param width defines the new width
  29652. * @param height defines the new height
  29653. * @param depth defines the new depth (1 by default)
  29654. */
  29655. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29656. if (depth === void 0) { depth = 1; }
  29657. this.width = width;
  29658. this.height = height;
  29659. this.depth = depth;
  29660. this.baseWidth = width;
  29661. this.baseHeight = height;
  29662. this.baseDepth = depth;
  29663. this._size = width * height * depth;
  29664. };
  29665. /** @hidden */
  29666. InternalTexture.prototype._rebuild = function () {
  29667. var _this = this;
  29668. var proxy;
  29669. this.isReady = false;
  29670. this._cachedCoordinatesMode = null;
  29671. this._cachedWrapU = null;
  29672. this._cachedWrapV = null;
  29673. this._cachedAnisotropicFilteringLevel = null;
  29674. switch (this._dataSource) {
  29675. case InternalTexture.DATASOURCE_TEMP:
  29676. return;
  29677. case InternalTexture.DATASOURCE_URL:
  29678. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29679. _this.isReady = true;
  29680. }, null, this._buffer, undefined, this.format);
  29681. proxy._swapAndDie(this);
  29682. return;
  29683. case InternalTexture.DATASOURCE_RAW:
  29684. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29685. proxy._swapAndDie(this);
  29686. this.isReady = true;
  29687. return;
  29688. case InternalTexture.DATASOURCE_RAW3D:
  29689. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29690. proxy._swapAndDie(this);
  29691. this.isReady = true;
  29692. return;
  29693. case InternalTexture.DATASOURCE_DYNAMIC:
  29694. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29695. proxy._swapAndDie(this);
  29696. // The engine will make sure to update content so no need to flag it as isReady = true
  29697. return;
  29698. case InternalTexture.DATASOURCE_RENDERTARGET:
  29699. var options = new BABYLON.RenderTargetCreationOptions();
  29700. options.generateDepthBuffer = this._generateDepthBuffer;
  29701. options.generateMipMaps = this.generateMipMaps;
  29702. options.generateStencilBuffer = this._generateStencilBuffer;
  29703. options.samplingMode = this.samplingMode;
  29704. options.type = this.type;
  29705. if (this.isCube) {
  29706. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29707. }
  29708. else {
  29709. var size = {
  29710. width: this.width,
  29711. height: this.height
  29712. };
  29713. proxy = this._engine.createRenderTargetTexture(size, options);
  29714. }
  29715. proxy._swapAndDie(this);
  29716. this.isReady = true;
  29717. return;
  29718. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29719. var depthTextureOptions = {
  29720. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29721. comparisonFunction: this._comparisonFunction,
  29722. generateStencil: this._generateStencilBuffer,
  29723. isCube: this.isCube
  29724. };
  29725. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29726. proxy._swapAndDie(this);
  29727. this.isReady = true;
  29728. return;
  29729. case InternalTexture.DATASOURCE_CUBE:
  29730. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29731. _this.isReady = true;
  29732. }, null, this.format, this._extension);
  29733. proxy._swapAndDie(this);
  29734. return;
  29735. case InternalTexture.DATASOURCE_CUBERAW:
  29736. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29737. proxy._swapAndDie(this);
  29738. this.isReady = true;
  29739. return;
  29740. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29741. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29742. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29743. _this.isReady = true;
  29744. });
  29745. proxy._swapAndDie(this);
  29746. return;
  29747. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29748. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29749. if (proxy) {
  29750. proxy._swapAndDie(_this);
  29751. }
  29752. _this.isReady = true;
  29753. }, null, this.format, this._extension);
  29754. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29755. return;
  29756. }
  29757. };
  29758. InternalTexture.prototype._swapAndDie = function (target) {
  29759. target._webGLTexture = this._webGLTexture;
  29760. if (this._framebuffer) {
  29761. target._framebuffer = this._framebuffer;
  29762. }
  29763. if (this._depthStencilBuffer) {
  29764. target._depthStencilBuffer = this._depthStencilBuffer;
  29765. }
  29766. if (this._lodTextureHigh) {
  29767. if (target._lodTextureHigh) {
  29768. target._lodTextureHigh.dispose();
  29769. }
  29770. target._lodTextureHigh = this._lodTextureHigh;
  29771. }
  29772. if (this._lodTextureMid) {
  29773. if (target._lodTextureMid) {
  29774. target._lodTextureMid.dispose();
  29775. }
  29776. target._lodTextureMid = this._lodTextureMid;
  29777. }
  29778. if (this._lodTextureLow) {
  29779. if (target._lodTextureLow) {
  29780. target._lodTextureLow.dispose();
  29781. }
  29782. target._lodTextureLow = this._lodTextureLow;
  29783. }
  29784. var cache = this._engine.getLoadedTexturesCache();
  29785. var index = cache.indexOf(this);
  29786. if (index !== -1) {
  29787. cache.splice(index, 1);
  29788. }
  29789. };
  29790. /**
  29791. * Dispose the current allocated resources
  29792. */
  29793. InternalTexture.prototype.dispose = function () {
  29794. if (!this._webGLTexture) {
  29795. return;
  29796. }
  29797. this._references--;
  29798. if (this._references === 0) {
  29799. this._engine._releaseTexture(this);
  29800. this._webGLTexture = null;
  29801. this.previous = null;
  29802. this.next = null;
  29803. }
  29804. };
  29805. /**
  29806. * The source of the texture data is unknown
  29807. */
  29808. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29809. /**
  29810. * Texture data comes from an URL
  29811. */
  29812. InternalTexture.DATASOURCE_URL = 1;
  29813. /**
  29814. * Texture data is only used for temporary storage
  29815. */
  29816. InternalTexture.DATASOURCE_TEMP = 2;
  29817. /**
  29818. * Texture data comes from raw data (ArrayBuffer)
  29819. */
  29820. InternalTexture.DATASOURCE_RAW = 3;
  29821. /**
  29822. * Texture content is dynamic (video or dynamic texture)
  29823. */
  29824. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29825. /**
  29826. * Texture content is generated by rendering to it
  29827. */
  29828. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29829. /**
  29830. * Texture content is part of a multi render target process
  29831. */
  29832. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29833. /**
  29834. * Texture data comes from a cube data file
  29835. */
  29836. InternalTexture.DATASOURCE_CUBE = 7;
  29837. /**
  29838. * Texture data comes from a raw cube data
  29839. */
  29840. InternalTexture.DATASOURCE_CUBERAW = 8;
  29841. /**
  29842. * Texture data come from a prefiltered cube data file
  29843. */
  29844. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29845. /**
  29846. * Texture content is raw 3D data
  29847. */
  29848. InternalTexture.DATASOURCE_RAW3D = 10;
  29849. /**
  29850. * Texture content is a depth texture
  29851. */
  29852. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29853. /**
  29854. * Texture data comes from a raw cube data encoded with RGBD
  29855. */
  29856. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29857. return InternalTexture;
  29858. }());
  29859. BABYLON.InternalTexture = InternalTexture;
  29860. })(BABYLON || (BABYLON = {}));
  29861. //# sourceMappingURL=babylon.internalTexture.js.map
  29862. var BABYLON;
  29863. (function (BABYLON) {
  29864. var BaseTexture = /** @class */ (function () {
  29865. function BaseTexture(scene) {
  29866. this._hasAlpha = false;
  29867. this.getAlphaFromRGB = false;
  29868. this.level = 1;
  29869. this.coordinatesIndex = 0;
  29870. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29871. /**
  29872. * | Value | Type | Description |
  29873. * | ----- | ------------------ | ----------- |
  29874. * | 0 | CLAMP_ADDRESSMODE | |
  29875. * | 1 | WRAP_ADDRESSMODE | |
  29876. * | 2 | MIRROR_ADDRESSMODE | |
  29877. */
  29878. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29879. /**
  29880. * | Value | Type | Description |
  29881. * | ----- | ------------------ | ----------- |
  29882. * | 0 | CLAMP_ADDRESSMODE | |
  29883. * | 1 | WRAP_ADDRESSMODE | |
  29884. * | 2 | MIRROR_ADDRESSMODE | |
  29885. */
  29886. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29887. /**
  29888. * | Value | Type | Description |
  29889. * | ----- | ------------------ | ----------- |
  29890. * | 0 | CLAMP_ADDRESSMODE | |
  29891. * | 1 | WRAP_ADDRESSMODE | |
  29892. * | 2 | MIRROR_ADDRESSMODE | |
  29893. */
  29894. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29895. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29896. this.isCube = false;
  29897. this.is3D = false;
  29898. this.gammaSpace = true;
  29899. this.invertZ = false;
  29900. this.lodLevelInAlpha = false;
  29901. this.isRenderTarget = false;
  29902. this.animations = new Array();
  29903. /**
  29904. * An event triggered when the texture is disposed.
  29905. */
  29906. this.onDisposeObservable = new BABYLON.Observable();
  29907. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29908. this._cachedSize = BABYLON.Size.Zero();
  29909. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29910. if (this._scene) {
  29911. this._scene.textures.push(this);
  29912. }
  29913. this._uid = null;
  29914. }
  29915. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29916. get: function () {
  29917. return this._hasAlpha;
  29918. },
  29919. set: function (value) {
  29920. if (this._hasAlpha === value) {
  29921. return;
  29922. }
  29923. this._hasAlpha = value;
  29924. if (this._scene) {
  29925. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29926. }
  29927. },
  29928. enumerable: true,
  29929. configurable: true
  29930. });
  29931. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29932. get: function () {
  29933. return this._coordinatesMode;
  29934. },
  29935. /**
  29936. * How a texture is mapped.
  29937. *
  29938. * | Value | Type | Description |
  29939. * | ----- | ----------------------------------- | ----------- |
  29940. * | 0 | EXPLICIT_MODE | |
  29941. * | 1 | SPHERICAL_MODE | |
  29942. * | 2 | PLANAR_MODE | |
  29943. * | 3 | CUBIC_MODE | |
  29944. * | 4 | PROJECTION_MODE | |
  29945. * | 5 | SKYBOX_MODE | |
  29946. * | 6 | INVCUBIC_MODE | |
  29947. * | 7 | EQUIRECTANGULAR_MODE | |
  29948. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29949. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29950. */
  29951. set: function (value) {
  29952. if (this._coordinatesMode === value) {
  29953. return;
  29954. }
  29955. this._coordinatesMode = value;
  29956. if (this._scene) {
  29957. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29958. }
  29959. },
  29960. enumerable: true,
  29961. configurable: true
  29962. });
  29963. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29964. /**
  29965. * Gets whether or not the texture contains RGBD data.
  29966. */
  29967. get: function () {
  29968. return this._texture != null && this._texture._isRGBD;
  29969. },
  29970. enumerable: true,
  29971. configurable: true
  29972. });
  29973. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29974. get: function () {
  29975. if (this._texture)
  29976. return this._texture._lodGenerationOffset;
  29977. return 0.0;
  29978. },
  29979. set: function (value) {
  29980. if (this._texture)
  29981. this._texture._lodGenerationOffset = value;
  29982. },
  29983. enumerable: true,
  29984. configurable: true
  29985. });
  29986. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29987. get: function () {
  29988. if (this._texture)
  29989. return this._texture._lodGenerationScale;
  29990. return 0.0;
  29991. },
  29992. set: function (value) {
  29993. if (this._texture)
  29994. this._texture._lodGenerationScale = value;
  29995. },
  29996. enumerable: true,
  29997. configurable: true
  29998. });
  29999. Object.defineProperty(BaseTexture.prototype, "uid", {
  30000. get: function () {
  30001. if (!this._uid) {
  30002. this._uid = BABYLON.Tools.RandomId();
  30003. }
  30004. return this._uid;
  30005. },
  30006. enumerable: true,
  30007. configurable: true
  30008. });
  30009. BaseTexture.prototype.toString = function () {
  30010. return this.name;
  30011. };
  30012. BaseTexture.prototype.getClassName = function () {
  30013. return "BaseTexture";
  30014. };
  30015. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30016. set: function (callback) {
  30017. if (this._onDisposeObserver) {
  30018. this.onDisposeObservable.remove(this._onDisposeObserver);
  30019. }
  30020. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30021. },
  30022. enumerable: true,
  30023. configurable: true
  30024. });
  30025. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30026. get: function () {
  30027. return true;
  30028. },
  30029. enumerable: true,
  30030. configurable: true
  30031. });
  30032. BaseTexture.prototype.getScene = function () {
  30033. return this._scene;
  30034. };
  30035. BaseTexture.prototype.getTextureMatrix = function () {
  30036. return BABYLON.Matrix.IdentityReadOnly;
  30037. };
  30038. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30039. return BABYLON.Matrix.IdentityReadOnly;
  30040. };
  30041. BaseTexture.prototype.getInternalTexture = function () {
  30042. return this._texture;
  30043. };
  30044. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30045. return !this.isBlocking || this.isReady();
  30046. };
  30047. BaseTexture.prototype.isReady = function () {
  30048. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30049. this.delayLoad();
  30050. return false;
  30051. }
  30052. if (this._texture) {
  30053. return this._texture.isReady;
  30054. }
  30055. return false;
  30056. };
  30057. BaseTexture.prototype.getSize = function () {
  30058. if (this._texture) {
  30059. if (this._texture.width) {
  30060. this._cachedSize.width = this._texture.width;
  30061. this._cachedSize.height = this._texture.height;
  30062. return this._cachedSize;
  30063. }
  30064. if (this._texture._size) {
  30065. this._cachedSize.width = this._texture._size;
  30066. this._cachedSize.height = this._texture._size;
  30067. return this._cachedSize;
  30068. }
  30069. }
  30070. return this._cachedSize;
  30071. };
  30072. BaseTexture.prototype.getBaseSize = function () {
  30073. if (!this.isReady() || !this._texture)
  30074. return BABYLON.Size.Zero();
  30075. if (this._texture._size) {
  30076. return new BABYLON.Size(this._texture._size, this._texture._size);
  30077. }
  30078. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30079. };
  30080. BaseTexture.prototype.scale = function (ratio) {
  30081. };
  30082. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30083. get: function () {
  30084. return false;
  30085. },
  30086. enumerable: true,
  30087. configurable: true
  30088. });
  30089. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30090. if (!this._scene) {
  30091. return null;
  30092. }
  30093. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30094. for (var index = 0; index < texturesCache.length; index++) {
  30095. var texturesCacheEntry = texturesCache[index];
  30096. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30097. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30098. texturesCacheEntry.incrementReferences();
  30099. return texturesCacheEntry;
  30100. }
  30101. }
  30102. }
  30103. return null;
  30104. };
  30105. BaseTexture.prototype._rebuild = function () {
  30106. };
  30107. BaseTexture.prototype.delayLoad = function () {
  30108. };
  30109. BaseTexture.prototype.clone = function () {
  30110. return null;
  30111. };
  30112. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30113. get: function () {
  30114. if (!this._texture) {
  30115. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30116. }
  30117. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30118. },
  30119. enumerable: true,
  30120. configurable: true
  30121. });
  30122. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30123. get: function () {
  30124. if (!this._texture) {
  30125. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30126. }
  30127. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30128. },
  30129. enumerable: true,
  30130. configurable: true
  30131. });
  30132. /**
  30133. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30134. * This will returns an RGBA array buffer containing either in values (0-255) or
  30135. * float values (0-1) depending of the underlying buffer type.
  30136. * @param faceIndex The face of the texture to read (in case of cube texture)
  30137. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30138. * @returns The Array buffer containing the pixels data.
  30139. */
  30140. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30141. if (faceIndex === void 0) { faceIndex = 0; }
  30142. if (level === void 0) { level = 0; }
  30143. if (!this._texture) {
  30144. return null;
  30145. }
  30146. var size = this.getSize();
  30147. var width = size.width;
  30148. var height = size.height;
  30149. var scene = this.getScene();
  30150. if (!scene) {
  30151. return null;
  30152. }
  30153. var engine = scene.getEngine();
  30154. if (level != 0) {
  30155. width = width / Math.pow(2, level);
  30156. height = height / Math.pow(2, level);
  30157. width = Math.round(width);
  30158. height = Math.round(height);
  30159. }
  30160. if (this._texture.isCube) {
  30161. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30162. }
  30163. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30164. };
  30165. BaseTexture.prototype.releaseInternalTexture = function () {
  30166. if (this._texture) {
  30167. this._texture.dispose();
  30168. this._texture = null;
  30169. }
  30170. };
  30171. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30172. get: function () {
  30173. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30174. return null;
  30175. }
  30176. if (!this._texture._sphericalPolynomial) {
  30177. this._texture._sphericalPolynomial =
  30178. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30179. }
  30180. return this._texture._sphericalPolynomial;
  30181. },
  30182. set: function (value) {
  30183. if (this._texture) {
  30184. this._texture._sphericalPolynomial = value;
  30185. }
  30186. },
  30187. enumerable: true,
  30188. configurable: true
  30189. });
  30190. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30191. get: function () {
  30192. if (this._texture) {
  30193. return this._texture._lodTextureHigh;
  30194. }
  30195. return null;
  30196. },
  30197. enumerable: true,
  30198. configurable: true
  30199. });
  30200. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30201. get: function () {
  30202. if (this._texture) {
  30203. return this._texture._lodTextureMid;
  30204. }
  30205. return null;
  30206. },
  30207. enumerable: true,
  30208. configurable: true
  30209. });
  30210. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30211. get: function () {
  30212. if (this._texture) {
  30213. return this._texture._lodTextureLow;
  30214. }
  30215. return null;
  30216. },
  30217. enumerable: true,
  30218. configurable: true
  30219. });
  30220. BaseTexture.prototype.dispose = function () {
  30221. if (!this._scene) {
  30222. return;
  30223. }
  30224. // Animations
  30225. this._scene.stopAnimation(this);
  30226. // Remove from scene
  30227. this._scene._removePendingData(this);
  30228. var index = this._scene.textures.indexOf(this);
  30229. if (index >= 0) {
  30230. this._scene.textures.splice(index, 1);
  30231. }
  30232. if (this._texture === undefined) {
  30233. return;
  30234. }
  30235. // Release
  30236. this.releaseInternalTexture();
  30237. // Callback
  30238. this.onDisposeObservable.notifyObservers(this);
  30239. this.onDisposeObservable.clear();
  30240. };
  30241. BaseTexture.prototype.serialize = function () {
  30242. if (!this.name) {
  30243. return null;
  30244. }
  30245. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30246. // Animations
  30247. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30248. return serializationObject;
  30249. };
  30250. BaseTexture.WhenAllReady = function (textures, callback) {
  30251. var numRemaining = textures.length;
  30252. if (numRemaining === 0) {
  30253. callback();
  30254. return;
  30255. }
  30256. var _loop_1 = function () {
  30257. texture = textures[i];
  30258. if (texture.isReady()) {
  30259. if (--numRemaining === 0) {
  30260. callback();
  30261. }
  30262. }
  30263. else {
  30264. onLoadObservable = texture.onLoadObservable;
  30265. var onLoadCallback_1 = function () {
  30266. onLoadObservable.removeCallback(onLoadCallback_1);
  30267. if (--numRemaining === 0) {
  30268. callback();
  30269. }
  30270. };
  30271. onLoadObservable.add(onLoadCallback_1);
  30272. }
  30273. };
  30274. var texture, onLoadObservable;
  30275. for (var i = 0; i < textures.length; i++) {
  30276. _loop_1();
  30277. }
  30278. };
  30279. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30280. __decorate([
  30281. BABYLON.serialize()
  30282. ], BaseTexture.prototype, "name", void 0);
  30283. __decorate([
  30284. BABYLON.serialize("hasAlpha")
  30285. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30286. __decorate([
  30287. BABYLON.serialize()
  30288. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30289. __decorate([
  30290. BABYLON.serialize()
  30291. ], BaseTexture.prototype, "level", void 0);
  30292. __decorate([
  30293. BABYLON.serialize()
  30294. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30295. __decorate([
  30296. BABYLON.serialize("coordinatesMode")
  30297. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30298. __decorate([
  30299. BABYLON.serialize()
  30300. ], BaseTexture.prototype, "wrapU", void 0);
  30301. __decorate([
  30302. BABYLON.serialize()
  30303. ], BaseTexture.prototype, "wrapV", void 0);
  30304. __decorate([
  30305. BABYLON.serialize()
  30306. ], BaseTexture.prototype, "wrapR", void 0);
  30307. __decorate([
  30308. BABYLON.serialize()
  30309. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30310. __decorate([
  30311. BABYLON.serialize()
  30312. ], BaseTexture.prototype, "isCube", void 0);
  30313. __decorate([
  30314. BABYLON.serialize()
  30315. ], BaseTexture.prototype, "is3D", void 0);
  30316. __decorate([
  30317. BABYLON.serialize()
  30318. ], BaseTexture.prototype, "gammaSpace", void 0);
  30319. __decorate([
  30320. BABYLON.serialize()
  30321. ], BaseTexture.prototype, "invertZ", void 0);
  30322. __decorate([
  30323. BABYLON.serialize()
  30324. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30325. __decorate([
  30326. BABYLON.serialize()
  30327. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30328. __decorate([
  30329. BABYLON.serialize()
  30330. ], BaseTexture.prototype, "lodGenerationScale", null);
  30331. __decorate([
  30332. BABYLON.serialize()
  30333. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30334. return BaseTexture;
  30335. }());
  30336. BABYLON.BaseTexture = BaseTexture;
  30337. })(BABYLON || (BABYLON = {}));
  30338. //# sourceMappingURL=babylon.baseTexture.js.map
  30339. var BABYLON;
  30340. (function (BABYLON) {
  30341. var Texture = /** @class */ (function (_super) {
  30342. __extends(Texture, _super);
  30343. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30344. if (noMipmap === void 0) { noMipmap = false; }
  30345. if (invertY === void 0) { invertY = true; }
  30346. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30347. if (onLoad === void 0) { onLoad = null; }
  30348. if (onError === void 0) { onError = null; }
  30349. if (buffer === void 0) { buffer = null; }
  30350. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30351. var _this = _super.call(this, scene) || this;
  30352. _this.uOffset = 0;
  30353. _this.vOffset = 0;
  30354. _this.uScale = 1.0;
  30355. _this.vScale = 1.0;
  30356. _this.uAng = 0;
  30357. _this.vAng = 0;
  30358. _this.wAng = 0;
  30359. /**
  30360. * Defines the center of rotation (U)
  30361. */
  30362. _this.uRotationCenter = 0.5;
  30363. /**
  30364. * Defines the center of rotation (V)
  30365. */
  30366. _this.vRotationCenter = 0.5;
  30367. /**
  30368. * Defines the center of rotation (W)
  30369. */
  30370. _this.wRotationCenter = 0.5;
  30371. _this._isBlocking = true;
  30372. _this.name = url || "";
  30373. _this.url = url;
  30374. _this._noMipmap = noMipmap;
  30375. _this._invertY = invertY;
  30376. _this._samplingMode = samplingMode;
  30377. _this._buffer = buffer;
  30378. _this._deleteBuffer = deleteBuffer;
  30379. if (format) {
  30380. _this._format = format;
  30381. }
  30382. scene = _this.getScene();
  30383. if (!scene) {
  30384. return _this;
  30385. }
  30386. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30387. var load = function () {
  30388. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30389. _this.onLoadObservable.notifyObservers(_this);
  30390. }
  30391. if (onLoad) {
  30392. onLoad();
  30393. }
  30394. if (!_this.isBlocking && scene) {
  30395. scene.resetCachedMaterial();
  30396. }
  30397. };
  30398. if (!_this.url) {
  30399. _this._delayedOnLoad = load;
  30400. _this._delayedOnError = onError;
  30401. return _this;
  30402. }
  30403. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30404. if (!_this._texture) {
  30405. if (!scene.useDelayedTextureLoading) {
  30406. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30407. if (deleteBuffer) {
  30408. delete _this._buffer;
  30409. }
  30410. }
  30411. else {
  30412. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30413. _this._delayedOnLoad = load;
  30414. _this._delayedOnError = onError;
  30415. }
  30416. }
  30417. else {
  30418. if (_this._texture.isReady) {
  30419. BABYLON.Tools.SetImmediate(function () { return load(); });
  30420. }
  30421. else {
  30422. _this._texture.onLoadedObservable.add(load);
  30423. }
  30424. }
  30425. return _this;
  30426. }
  30427. Object.defineProperty(Texture.prototype, "noMipmap", {
  30428. get: function () {
  30429. return this._noMipmap;
  30430. },
  30431. enumerable: true,
  30432. configurable: true
  30433. });
  30434. Object.defineProperty(Texture.prototype, "isBlocking", {
  30435. get: function () {
  30436. return this._isBlocking;
  30437. },
  30438. set: function (value) {
  30439. this._isBlocking = value;
  30440. },
  30441. enumerable: true,
  30442. configurable: true
  30443. });
  30444. Object.defineProperty(Texture.prototype, "samplingMode", {
  30445. get: function () {
  30446. return this._samplingMode;
  30447. },
  30448. enumerable: true,
  30449. configurable: true
  30450. });
  30451. /**
  30452. * Update the url (and optional buffer) of this texture if url was null during construction.
  30453. * @param url the url of the texture
  30454. * @param buffer the buffer of the texture (defaults to null)
  30455. */
  30456. Texture.prototype.updateURL = function (url, buffer) {
  30457. if (buffer === void 0) { buffer = null; }
  30458. if (this.url) {
  30459. throw new Error("URL is already set");
  30460. }
  30461. this.url = url;
  30462. this._buffer = buffer;
  30463. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30464. this.delayLoad();
  30465. };
  30466. Texture.prototype.delayLoad = function () {
  30467. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30468. return;
  30469. }
  30470. var scene = this.getScene();
  30471. if (!scene) {
  30472. return;
  30473. }
  30474. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30475. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30476. if (!this._texture) {
  30477. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30478. if (this._deleteBuffer) {
  30479. delete this._buffer;
  30480. }
  30481. }
  30482. else {
  30483. if (this._delayedOnLoad) {
  30484. if (this._texture.isReady) {
  30485. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30486. }
  30487. else {
  30488. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30489. }
  30490. }
  30491. }
  30492. this._delayedOnLoad = null;
  30493. this._delayedOnError = null;
  30494. };
  30495. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30496. if (!this._texture) {
  30497. return;
  30498. }
  30499. var scene = this.getScene();
  30500. if (!scene) {
  30501. return;
  30502. }
  30503. this._samplingMode = samplingMode;
  30504. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30505. };
  30506. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30507. x *= this.uScale;
  30508. y *= this.vScale;
  30509. x -= this.uRotationCenter * this.uScale;
  30510. y -= this.vRotationCenter * this.vScale;
  30511. z -= this.wRotationCenter;
  30512. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30513. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30514. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30515. t.z += this.wRotationCenter;
  30516. };
  30517. Texture.prototype.getTextureMatrix = function () {
  30518. var _this = this;
  30519. if (this.uOffset === this._cachedUOffset &&
  30520. this.vOffset === this._cachedVOffset &&
  30521. this.uScale === this._cachedUScale &&
  30522. this.vScale === this._cachedVScale &&
  30523. this.uAng === this._cachedUAng &&
  30524. this.vAng === this._cachedVAng &&
  30525. this.wAng === this._cachedWAng) {
  30526. return this._cachedTextureMatrix;
  30527. }
  30528. this._cachedUOffset = this.uOffset;
  30529. this._cachedVOffset = this.vOffset;
  30530. this._cachedUScale = this.uScale;
  30531. this._cachedVScale = this.vScale;
  30532. this._cachedUAng = this.uAng;
  30533. this._cachedVAng = this.vAng;
  30534. this._cachedWAng = this.wAng;
  30535. if (!this._cachedTextureMatrix) {
  30536. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30537. this._rowGenerationMatrix = new BABYLON.Matrix();
  30538. this._t0 = BABYLON.Vector3.Zero();
  30539. this._t1 = BABYLON.Vector3.Zero();
  30540. this._t2 = BABYLON.Vector3.Zero();
  30541. }
  30542. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30543. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30544. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30545. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30546. this._t1.subtractInPlace(this._t0);
  30547. this._t2.subtractInPlace(this._t0);
  30548. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30549. this._cachedTextureMatrix.m[0] = this._t1.x;
  30550. this._cachedTextureMatrix.m[1] = this._t1.y;
  30551. this._cachedTextureMatrix.m[2] = this._t1.z;
  30552. this._cachedTextureMatrix.m[4] = this._t2.x;
  30553. this._cachedTextureMatrix.m[5] = this._t2.y;
  30554. this._cachedTextureMatrix.m[6] = this._t2.z;
  30555. this._cachedTextureMatrix.m[8] = this._t0.x;
  30556. this._cachedTextureMatrix.m[9] = this._t0.y;
  30557. this._cachedTextureMatrix.m[10] = this._t0.z;
  30558. var scene = this.getScene();
  30559. if (!scene) {
  30560. return this._cachedTextureMatrix;
  30561. }
  30562. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30563. return mat.hasTexture(_this);
  30564. });
  30565. return this._cachedTextureMatrix;
  30566. };
  30567. Texture.prototype.getReflectionTextureMatrix = function () {
  30568. var _this = this;
  30569. var scene = this.getScene();
  30570. if (!scene) {
  30571. return this._cachedTextureMatrix;
  30572. }
  30573. if (this.uOffset === this._cachedUOffset &&
  30574. this.vOffset === this._cachedVOffset &&
  30575. this.uScale === this._cachedUScale &&
  30576. this.vScale === this._cachedVScale &&
  30577. this.coordinatesMode === this._cachedCoordinatesMode) {
  30578. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30579. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30580. return this._cachedTextureMatrix;
  30581. }
  30582. }
  30583. else {
  30584. return this._cachedTextureMatrix;
  30585. }
  30586. }
  30587. if (!this._cachedTextureMatrix) {
  30588. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30589. }
  30590. if (!this._projectionModeMatrix) {
  30591. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30592. }
  30593. this._cachedUOffset = this.uOffset;
  30594. this._cachedVOffset = this.vOffset;
  30595. this._cachedUScale = this.uScale;
  30596. this._cachedVScale = this.vScale;
  30597. this._cachedCoordinatesMode = this.coordinatesMode;
  30598. switch (this.coordinatesMode) {
  30599. case Texture.PLANAR_MODE:
  30600. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30601. this._cachedTextureMatrix[0] = this.uScale;
  30602. this._cachedTextureMatrix[5] = this.vScale;
  30603. this._cachedTextureMatrix[12] = this.uOffset;
  30604. this._cachedTextureMatrix[13] = this.vOffset;
  30605. break;
  30606. case Texture.PROJECTION_MODE:
  30607. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30608. this._projectionModeMatrix.m[0] = 0.5;
  30609. this._projectionModeMatrix.m[5] = -0.5;
  30610. this._projectionModeMatrix.m[10] = 0.0;
  30611. this._projectionModeMatrix.m[12] = 0.5;
  30612. this._projectionModeMatrix.m[13] = 0.5;
  30613. this._projectionModeMatrix.m[14] = 1.0;
  30614. this._projectionModeMatrix.m[15] = 1.0;
  30615. var projectionMatrix = scene.getProjectionMatrix();
  30616. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30617. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30618. break;
  30619. default:
  30620. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30621. break;
  30622. }
  30623. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30624. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30625. });
  30626. return this._cachedTextureMatrix;
  30627. };
  30628. Texture.prototype.clone = function () {
  30629. var _this = this;
  30630. return BABYLON.SerializationHelper.Clone(function () {
  30631. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30632. }, this);
  30633. };
  30634. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30635. get: function () {
  30636. if (!this._onLoadObservable) {
  30637. this._onLoadObservable = new BABYLON.Observable();
  30638. }
  30639. return this._onLoadObservable;
  30640. },
  30641. enumerable: true,
  30642. configurable: true
  30643. });
  30644. Texture.prototype.serialize = function () {
  30645. var serializationObject = _super.prototype.serialize.call(this);
  30646. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30647. serializationObject.base64String = this._buffer;
  30648. serializationObject.name = serializationObject.name.replace("data:", "");
  30649. }
  30650. serializationObject.invertY = this._invertY;
  30651. serializationObject.samplingMode = this.samplingMode;
  30652. return serializationObject;
  30653. };
  30654. Texture.prototype.getClassName = function () {
  30655. return "Texture";
  30656. };
  30657. Texture.prototype.dispose = function () {
  30658. _super.prototype.dispose.call(this);
  30659. if (this._onLoadObservable) {
  30660. this._onLoadObservable.clear();
  30661. this._onLoadObservable = null;
  30662. }
  30663. this._delayedOnLoad = null;
  30664. this._delayedOnError = null;
  30665. };
  30666. // Statics
  30667. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30668. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30669. if (onLoad === void 0) { onLoad = null; }
  30670. if (onError === void 0) { onError = null; }
  30671. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30672. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30673. };
  30674. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30675. if (parsedTexture.customType) {
  30676. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30677. // Update Sampling Mode
  30678. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30679. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30680. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30681. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30682. }
  30683. }
  30684. return parsedCustomTexture;
  30685. }
  30686. if (parsedTexture.isCube) {
  30687. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30688. }
  30689. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30690. return null;
  30691. }
  30692. var texture = BABYLON.SerializationHelper.Parse(function () {
  30693. var generateMipMaps = true;
  30694. if (parsedTexture.noMipmap) {
  30695. generateMipMaps = false;
  30696. }
  30697. if (parsedTexture.mirrorPlane) {
  30698. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30699. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30700. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30701. return mirrorTexture;
  30702. }
  30703. else if (parsedTexture.isRenderTarget) {
  30704. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30705. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30706. return renderTargetTexture;
  30707. }
  30708. else {
  30709. var texture;
  30710. if (parsedTexture.base64String) {
  30711. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30712. }
  30713. else {
  30714. var url = rootUrl + parsedTexture.name;
  30715. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30716. url = parsedTexture.url;
  30717. }
  30718. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30719. }
  30720. return texture;
  30721. }
  30722. }, parsedTexture, scene);
  30723. // Update Sampling Mode
  30724. if (parsedTexture.samplingMode) {
  30725. var sampling = parsedTexture.samplingMode;
  30726. if (texture._samplingMode !== sampling) {
  30727. texture.updateSamplingMode(sampling);
  30728. }
  30729. }
  30730. // Animations
  30731. if (parsedTexture.animations) {
  30732. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30733. var parsedAnimation = parsedTexture.animations[animationIndex];
  30734. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30735. }
  30736. }
  30737. return texture;
  30738. };
  30739. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30740. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30741. if (noMipmap === void 0) { noMipmap = false; }
  30742. if (invertY === void 0) { invertY = true; }
  30743. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30744. if (onLoad === void 0) { onLoad = null; }
  30745. if (onError === void 0) { onError = null; }
  30746. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30747. if (name.substr(0, 5) !== "data:") {
  30748. name = "data:" + name;
  30749. }
  30750. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30751. };
  30752. // Constants
  30753. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30754. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30755. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30756. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30757. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30758. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30759. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30760. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30761. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30762. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30763. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30764. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30765. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30766. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30767. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30768. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30769. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30770. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30771. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30772. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30773. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30774. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30775. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30776. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30777. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30778. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30779. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30780. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30781. /**
  30782. * 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
  30783. */
  30784. Texture.UseSerializedUrlIfAny = false;
  30785. __decorate([
  30786. BABYLON.serialize()
  30787. ], Texture.prototype, "url", void 0);
  30788. __decorate([
  30789. BABYLON.serialize()
  30790. ], Texture.prototype, "uOffset", void 0);
  30791. __decorate([
  30792. BABYLON.serialize()
  30793. ], Texture.prototype, "vOffset", void 0);
  30794. __decorate([
  30795. BABYLON.serialize()
  30796. ], Texture.prototype, "uScale", void 0);
  30797. __decorate([
  30798. BABYLON.serialize()
  30799. ], Texture.prototype, "vScale", void 0);
  30800. __decorate([
  30801. BABYLON.serialize()
  30802. ], Texture.prototype, "uAng", void 0);
  30803. __decorate([
  30804. BABYLON.serialize()
  30805. ], Texture.prototype, "vAng", void 0);
  30806. __decorate([
  30807. BABYLON.serialize()
  30808. ], Texture.prototype, "wAng", void 0);
  30809. __decorate([
  30810. BABYLON.serialize()
  30811. ], Texture.prototype, "uRotationCenter", void 0);
  30812. __decorate([
  30813. BABYLON.serialize()
  30814. ], Texture.prototype, "vRotationCenter", void 0);
  30815. __decorate([
  30816. BABYLON.serialize()
  30817. ], Texture.prototype, "wRotationCenter", void 0);
  30818. __decorate([
  30819. BABYLON.serialize()
  30820. ], Texture.prototype, "isBlocking", null);
  30821. return Texture;
  30822. }(BABYLON.BaseTexture));
  30823. BABYLON.Texture = Texture;
  30824. })(BABYLON || (BABYLON = {}));
  30825. //# sourceMappingURL=babylon.texture.js.map
  30826. var BABYLON;
  30827. (function (BABYLON) {
  30828. /**
  30829. * @hidden
  30830. **/
  30831. var _InstancesBatch = /** @class */ (function () {
  30832. function _InstancesBatch() {
  30833. this.mustReturn = false;
  30834. this.visibleInstances = new Array();
  30835. this.renderSelf = new Array();
  30836. }
  30837. return _InstancesBatch;
  30838. }());
  30839. BABYLON._InstancesBatch = _InstancesBatch;
  30840. var Mesh = /** @class */ (function (_super) {
  30841. __extends(Mesh, _super);
  30842. /**
  30843. * @constructor
  30844. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30845. * @param {Scene} scene The scene to add this mesh to.
  30846. * @param {Node} parent The parent of this mesh, if it has one
  30847. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30848. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30849. * When false, achieved by calling a clone(), also passing False.
  30850. * This will make creation of children, recursive.
  30851. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30852. */
  30853. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30854. if (scene === void 0) { scene = null; }
  30855. if (parent === void 0) { parent = null; }
  30856. if (source === void 0) { source = null; }
  30857. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30858. var _this = _super.call(this, name, scene) || this;
  30859. // Events
  30860. /**
  30861. * An event triggered before rendering the mesh
  30862. */
  30863. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30864. /**
  30865. * An event triggered after rendering the mesh
  30866. */
  30867. _this.onAfterRenderObservable = new BABYLON.Observable();
  30868. /**
  30869. * An event triggered before drawing the mesh
  30870. */
  30871. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30872. // Members
  30873. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30874. _this.instances = new Array();
  30875. _this._LODLevels = new Array();
  30876. _this._visibleInstances = {};
  30877. _this._renderIdForInstances = new Array();
  30878. _this._batchCache = new _InstancesBatch();
  30879. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30880. // Use by builder only to know what orientation were the mesh build in.
  30881. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30882. _this.overrideMaterialSideOrientation = null;
  30883. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30884. // Will be used to save a source mesh reference, If any
  30885. _this._source = null;
  30886. scene = _this.getScene();
  30887. if (source) {
  30888. // Geometry
  30889. if (source._geometry) {
  30890. source._geometry.applyToMesh(_this);
  30891. }
  30892. // Deep copy
  30893. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30894. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  30895. // Source mesh
  30896. _this._source = source;
  30897. // Metadata
  30898. if (source.metadata && source.metadata.clone) {
  30899. _this.metadata = source.metadata.clone();
  30900. }
  30901. else {
  30902. _this.metadata = source.metadata;
  30903. }
  30904. // Tags
  30905. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30906. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30907. }
  30908. // Parent
  30909. _this.parent = source.parent;
  30910. // Pivot
  30911. _this.setPivotMatrix(source.getPivotMatrix());
  30912. _this.id = name + "." + source.id;
  30913. // Material
  30914. _this.material = source.material;
  30915. var index;
  30916. if (!doNotCloneChildren) {
  30917. // Children
  30918. var directDescendants = source.getDescendants(true);
  30919. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30920. var child = directDescendants[index_1];
  30921. if (child.clone) {
  30922. child.clone(name + "." + child.name, _this);
  30923. }
  30924. }
  30925. }
  30926. // Physics clone
  30927. var physicsEngine = _this.getScene().getPhysicsEngine();
  30928. if (clonePhysicsImpostor && physicsEngine) {
  30929. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30930. if (impostor) {
  30931. _this.physicsImpostor = impostor.clone(_this);
  30932. }
  30933. }
  30934. // Particles
  30935. for (index = 0; index < scene.particleSystems.length; index++) {
  30936. var system = scene.particleSystems[index];
  30937. if (system.emitter === source) {
  30938. system.clone(system.name, _this);
  30939. }
  30940. }
  30941. _this.refreshBoundingInfo();
  30942. _this.computeWorldMatrix(true);
  30943. }
  30944. // Parent
  30945. if (parent !== null) {
  30946. _this.parent = parent;
  30947. }
  30948. return _this;
  30949. }
  30950. Object.defineProperty(Mesh, "FRONTSIDE", {
  30951. /**
  30952. * Mesh side orientation : usually the external or front surface
  30953. */
  30954. get: function () {
  30955. return Mesh._FRONTSIDE;
  30956. },
  30957. enumerable: true,
  30958. configurable: true
  30959. });
  30960. Object.defineProperty(Mesh, "BACKSIDE", {
  30961. /**
  30962. * Mesh side orientation : usually the internal or back surface
  30963. */
  30964. get: function () {
  30965. return Mesh._BACKSIDE;
  30966. },
  30967. enumerable: true,
  30968. configurable: true
  30969. });
  30970. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30971. /**
  30972. * Mesh side orientation : both internal and external or front and back surfaces
  30973. */
  30974. get: function () {
  30975. return Mesh._DOUBLESIDE;
  30976. },
  30977. enumerable: true,
  30978. configurable: true
  30979. });
  30980. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30981. /**
  30982. * Mesh side orientation : by default, `FRONTSIDE`
  30983. */
  30984. get: function () {
  30985. return Mesh._DEFAULTSIDE;
  30986. },
  30987. enumerable: true,
  30988. configurable: true
  30989. });
  30990. Object.defineProperty(Mesh, "NO_CAP", {
  30991. /**
  30992. * Mesh cap setting : no cap
  30993. */
  30994. get: function () {
  30995. return Mesh._NO_CAP;
  30996. },
  30997. enumerable: true,
  30998. configurable: true
  30999. });
  31000. Object.defineProperty(Mesh, "CAP_START", {
  31001. /**
  31002. * Mesh cap setting : one cap at the beginning of the mesh
  31003. */
  31004. get: function () {
  31005. return Mesh._CAP_START;
  31006. },
  31007. enumerable: true,
  31008. configurable: true
  31009. });
  31010. Object.defineProperty(Mesh, "CAP_END", {
  31011. /**
  31012. * Mesh cap setting : one cap at the end of the mesh
  31013. */
  31014. get: function () {
  31015. return Mesh._CAP_END;
  31016. },
  31017. enumerable: true,
  31018. configurable: true
  31019. });
  31020. Object.defineProperty(Mesh, "CAP_ALL", {
  31021. /**
  31022. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31023. */
  31024. get: function () {
  31025. return Mesh._CAP_ALL;
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31031. set: function (callback) {
  31032. if (this._onBeforeDrawObserver) {
  31033. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31034. }
  31035. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31036. },
  31037. enumerable: true,
  31038. configurable: true
  31039. });
  31040. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31041. get: function () {
  31042. return this._morphTargetManager;
  31043. },
  31044. set: function (value) {
  31045. if (this._morphTargetManager === value) {
  31046. return;
  31047. }
  31048. this._morphTargetManager = value;
  31049. this._syncGeometryWithMorphTargetManager();
  31050. },
  31051. enumerable: true,
  31052. configurable: true
  31053. });
  31054. Object.defineProperty(Mesh.prototype, "source", {
  31055. get: function () {
  31056. return this._source;
  31057. },
  31058. enumerable: true,
  31059. configurable: true
  31060. });
  31061. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31062. get: function () {
  31063. return this._unIndexed;
  31064. },
  31065. set: function (value) {
  31066. if (this._unIndexed !== value) {
  31067. this._unIndexed = value;
  31068. this._markSubMeshesAsAttributesDirty();
  31069. }
  31070. },
  31071. enumerable: true,
  31072. configurable: true
  31073. });
  31074. // Methods
  31075. /**
  31076. * Returns the string "Mesh".
  31077. */
  31078. Mesh.prototype.getClassName = function () {
  31079. return "Mesh";
  31080. };
  31081. /**
  31082. * Returns a string.
  31083. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31084. */
  31085. Mesh.prototype.toString = function (fullDetails) {
  31086. var ret = _super.prototype.toString.call(this, fullDetails);
  31087. ret += ", n vertices: " + this.getTotalVertices();
  31088. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31089. if (this.animations) {
  31090. for (var i = 0; i < this.animations.length; i++) {
  31091. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31092. }
  31093. }
  31094. if (fullDetails) {
  31095. if (this._geometry) {
  31096. var ib = this.getIndices();
  31097. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31098. if (vb && ib) {
  31099. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31100. }
  31101. }
  31102. else {
  31103. ret += ", flat shading: UNKNOWN";
  31104. }
  31105. }
  31106. return ret;
  31107. };
  31108. Mesh.prototype._unBindEffect = function () {
  31109. _super.prototype._unBindEffect.call(this);
  31110. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31111. var instance = _a[_i];
  31112. instance._unBindEffect();
  31113. }
  31114. };
  31115. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31116. /**
  31117. * True if the mesh has some Levels Of Details (LOD).
  31118. * Returns a boolean.
  31119. */
  31120. get: function () {
  31121. return this._LODLevels.length > 0;
  31122. },
  31123. enumerable: true,
  31124. configurable: true
  31125. });
  31126. /**
  31127. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31128. * @returns an array of {BABYLON.MeshLODLevel}
  31129. */
  31130. Mesh.prototype.getLODLevels = function () {
  31131. return this._LODLevels;
  31132. };
  31133. Mesh.prototype._sortLODLevels = function () {
  31134. this._LODLevels.sort(function (a, b) {
  31135. if (a.distance < b.distance) {
  31136. return 1;
  31137. }
  31138. if (a.distance > b.distance) {
  31139. return -1;
  31140. }
  31141. return 0;
  31142. });
  31143. };
  31144. /**
  31145. * Add a mesh as LOD level triggered at the given distance.
  31146. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31147. * @param distance The distance from the center of the object to show this level
  31148. * @param mesh The mesh to be added as LOD level (can be null)
  31149. * @return This mesh (for chaining)
  31150. */
  31151. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31152. if (mesh && mesh._masterMesh) {
  31153. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31154. return this;
  31155. }
  31156. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31157. this._LODLevels.push(level);
  31158. if (mesh) {
  31159. mesh._masterMesh = this;
  31160. }
  31161. this._sortLODLevels();
  31162. return this;
  31163. };
  31164. /**
  31165. * Returns the LOD level mesh at the passed distance or null if not found.
  31166. * It is related to the method `addLODLevel(distance, mesh)`.
  31167. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31168. * Returns an object Mesh or `null`.
  31169. */
  31170. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31171. for (var index = 0; index < this._LODLevels.length; index++) {
  31172. var level = this._LODLevels[index];
  31173. if (level.distance === distance) {
  31174. return level.mesh;
  31175. }
  31176. }
  31177. return null;
  31178. };
  31179. /**
  31180. * Remove a mesh from the LOD array
  31181. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31182. * @param {Mesh} mesh The mesh to be removed.
  31183. * @return {Mesh} This mesh (for chaining)
  31184. */
  31185. Mesh.prototype.removeLODLevel = function (mesh) {
  31186. for (var index = 0; index < this._LODLevels.length; index++) {
  31187. if (this._LODLevels[index].mesh === mesh) {
  31188. this._LODLevels.splice(index, 1);
  31189. if (mesh) {
  31190. mesh._masterMesh = null;
  31191. }
  31192. }
  31193. }
  31194. this._sortLODLevels();
  31195. return this;
  31196. };
  31197. /**
  31198. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31199. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31200. */
  31201. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31202. if (!this._LODLevels || this._LODLevels.length === 0) {
  31203. return this;
  31204. }
  31205. var bSphere;
  31206. if (boundingSphere) {
  31207. bSphere = boundingSphere;
  31208. }
  31209. else {
  31210. var boundingInfo = this.getBoundingInfo();
  31211. bSphere = boundingInfo.boundingSphere;
  31212. }
  31213. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31214. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31215. if (this.onLODLevelSelection) {
  31216. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31217. }
  31218. return this;
  31219. }
  31220. for (var index = 0; index < this._LODLevels.length; index++) {
  31221. var level = this._LODLevels[index];
  31222. if (level.distance < distanceToCamera) {
  31223. if (level.mesh) {
  31224. level.mesh._preActivate();
  31225. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31226. }
  31227. if (this.onLODLevelSelection) {
  31228. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31229. }
  31230. return level.mesh;
  31231. }
  31232. }
  31233. if (this.onLODLevelSelection) {
  31234. this.onLODLevelSelection(distanceToCamera, this, this);
  31235. }
  31236. return this;
  31237. };
  31238. Object.defineProperty(Mesh.prototype, "geometry", {
  31239. /**
  31240. * Returns the mesh internal Geometry object.
  31241. */
  31242. get: function () {
  31243. return this._geometry;
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. /**
  31249. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31250. */
  31251. Mesh.prototype.getTotalVertices = function () {
  31252. if (this._geometry === null || this._geometry === undefined) {
  31253. return 0;
  31254. }
  31255. return this._geometry.getTotalVertices();
  31256. };
  31257. /**
  31258. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31259. * 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.
  31260. * You can force the copy with forceCopy === true
  31261. * Returns null if the mesh has no geometry or no vertex buffer.
  31262. * Possible `kind` values :
  31263. * - BABYLON.VertexBuffer.PositionKind
  31264. * - BABYLON.VertexBuffer.UVKind
  31265. * - BABYLON.VertexBuffer.UV2Kind
  31266. * - BABYLON.VertexBuffer.UV3Kind
  31267. * - BABYLON.VertexBuffer.UV4Kind
  31268. * - BABYLON.VertexBuffer.UV5Kind
  31269. * - BABYLON.VertexBuffer.UV6Kind
  31270. * - BABYLON.VertexBuffer.ColorKind
  31271. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31272. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31273. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31274. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31275. */
  31276. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31277. if (!this._geometry) {
  31278. return null;
  31279. }
  31280. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31281. };
  31282. /**
  31283. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31284. * Returns `null` if the mesh has no geometry.
  31285. * Possible `kind` values :
  31286. * - BABYLON.VertexBuffer.PositionKind
  31287. * - BABYLON.VertexBuffer.UVKind
  31288. * - BABYLON.VertexBuffer.UV2Kind
  31289. * - BABYLON.VertexBuffer.UV3Kind
  31290. * - BABYLON.VertexBuffer.UV4Kind
  31291. * - BABYLON.VertexBuffer.UV5Kind
  31292. * - BABYLON.VertexBuffer.UV6Kind
  31293. * - BABYLON.VertexBuffer.ColorKind
  31294. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31295. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31296. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31297. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31298. */
  31299. Mesh.prototype.getVertexBuffer = function (kind) {
  31300. if (!this._geometry) {
  31301. return null;
  31302. }
  31303. return this._geometry.getVertexBuffer(kind);
  31304. };
  31305. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31306. if (!this._geometry) {
  31307. if (this._delayInfo) {
  31308. return this._delayInfo.indexOf(kind) !== -1;
  31309. }
  31310. return false;
  31311. }
  31312. return this._geometry.isVerticesDataPresent(kind);
  31313. };
  31314. /**
  31315. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31316. * Possible `kind` values :
  31317. * - BABYLON.VertexBuffer.PositionKind
  31318. * - BABYLON.VertexBuffer.UVKind
  31319. * - BABYLON.VertexBuffer.UV2Kind
  31320. * - BABYLON.VertexBuffer.UV3Kind
  31321. * - BABYLON.VertexBuffer.UV4Kind
  31322. * - BABYLON.VertexBuffer.UV5Kind
  31323. * - BABYLON.VertexBuffer.UV6Kind
  31324. * - BABYLON.VertexBuffer.ColorKind
  31325. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31326. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31327. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31328. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31329. */
  31330. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31331. if (!this._geometry) {
  31332. if (this._delayInfo) {
  31333. return this._delayInfo.indexOf(kind) !== -1;
  31334. }
  31335. return false;
  31336. }
  31337. return this._geometry.isVertexBufferUpdatable(kind);
  31338. };
  31339. /**
  31340. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31341. * Possible `kind` values :
  31342. * - BABYLON.VertexBuffer.PositionKind
  31343. * - BABYLON.VertexBuffer.UVKind
  31344. * - BABYLON.VertexBuffer.UV2Kind
  31345. * - BABYLON.VertexBuffer.UV3Kind
  31346. * - BABYLON.VertexBuffer.UV4Kind
  31347. * - BABYLON.VertexBuffer.UV5Kind
  31348. * - BABYLON.VertexBuffer.UV6Kind
  31349. * - BABYLON.VertexBuffer.ColorKind
  31350. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31351. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31352. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31353. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31354. */
  31355. Mesh.prototype.getVerticesDataKinds = function () {
  31356. if (!this._geometry) {
  31357. var result = new Array();
  31358. if (this._delayInfo) {
  31359. this._delayInfo.forEach(function (kind, index, array) {
  31360. result.push(kind);
  31361. });
  31362. }
  31363. return result;
  31364. }
  31365. return this._geometry.getVerticesDataKinds();
  31366. };
  31367. /**
  31368. * Returns a positive integer : the total number of indices in this mesh geometry.
  31369. * Returns zero if the mesh has no geometry.
  31370. */
  31371. Mesh.prototype.getTotalIndices = function () {
  31372. if (!this._geometry) {
  31373. return 0;
  31374. }
  31375. return this._geometry.getTotalIndices();
  31376. };
  31377. /**
  31378. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31379. * 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.
  31380. * Returns an empty array if the mesh has no geometry.
  31381. */
  31382. Mesh.prototype.getIndices = function (copyWhenShared) {
  31383. if (!this._geometry) {
  31384. return [];
  31385. }
  31386. return this._geometry.getIndices(copyWhenShared);
  31387. };
  31388. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31389. get: function () {
  31390. return this._masterMesh !== null && this._masterMesh !== undefined;
  31391. },
  31392. enumerable: true,
  31393. configurable: true
  31394. });
  31395. /**
  31396. * Determine if the current mesh is ready to be rendered
  31397. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31398. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31399. * @returns true if all associated assets are ready (material, textures, shaders)
  31400. */
  31401. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31402. if (completeCheck === void 0) { completeCheck = false; }
  31403. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31404. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31405. return false;
  31406. }
  31407. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31408. return false;
  31409. }
  31410. if (!this.subMeshes || this.subMeshes.length === 0) {
  31411. return true;
  31412. }
  31413. if (!completeCheck) {
  31414. return true;
  31415. }
  31416. var engine = this.getEngine();
  31417. var scene = this.getScene();
  31418. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31419. this.computeWorldMatrix();
  31420. var mat = this.material || scene.defaultMaterial;
  31421. if (mat) {
  31422. if (mat.storeEffectOnSubMeshes) {
  31423. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31424. var subMesh = _a[_i];
  31425. var effectiveMaterial = subMesh.getMaterial();
  31426. if (effectiveMaterial) {
  31427. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31428. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31429. return false;
  31430. }
  31431. }
  31432. else {
  31433. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31434. return false;
  31435. }
  31436. }
  31437. }
  31438. }
  31439. }
  31440. else {
  31441. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31442. return false;
  31443. }
  31444. }
  31445. }
  31446. // Shadows
  31447. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31448. var light = _c[_b];
  31449. var generator = light.getShadowGenerator();
  31450. if (generator) {
  31451. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31452. var subMesh = _e[_d];
  31453. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31454. return false;
  31455. }
  31456. }
  31457. }
  31458. }
  31459. // LOD
  31460. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31461. var lod = _g[_f];
  31462. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31463. return false;
  31464. }
  31465. }
  31466. return true;
  31467. };
  31468. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31469. /**
  31470. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31471. * This property is pertinent only for updatable parametric shapes.
  31472. */
  31473. get: function () {
  31474. return this._areNormalsFrozen;
  31475. },
  31476. enumerable: true,
  31477. configurable: true
  31478. });
  31479. /**
  31480. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31481. * It has no effect at all on other shapes.
  31482. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31483. * Returns the Mesh.
  31484. */
  31485. Mesh.prototype.freezeNormals = function () {
  31486. this._areNormalsFrozen = true;
  31487. return this;
  31488. };
  31489. /**
  31490. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31491. * It has no effect at all on other shapes.
  31492. * It reactivates the mesh normals computation if it was previously frozen.
  31493. * Returns the Mesh.
  31494. */
  31495. Mesh.prototype.unfreezeNormals = function () {
  31496. this._areNormalsFrozen = false;
  31497. return this;
  31498. };
  31499. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31500. /**
  31501. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31502. */
  31503. set: function (count) {
  31504. this._overridenInstanceCount = count;
  31505. },
  31506. enumerable: true,
  31507. configurable: true
  31508. });
  31509. // Methods
  31510. Mesh.prototype._preActivate = function () {
  31511. var sceneRenderId = this.getScene().getRenderId();
  31512. if (this._preActivateId === sceneRenderId) {
  31513. return this;
  31514. }
  31515. this._preActivateId = sceneRenderId;
  31516. this._visibleInstances = null;
  31517. return this;
  31518. };
  31519. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31520. if (this._visibleInstances) {
  31521. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31522. }
  31523. return this;
  31524. };
  31525. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31526. if (!this._visibleInstances) {
  31527. this._visibleInstances = {};
  31528. this._visibleInstances.defaultRenderId = renderId;
  31529. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31530. }
  31531. if (!this._visibleInstances[renderId]) {
  31532. this._visibleInstances[renderId] = new Array();
  31533. }
  31534. this._visibleInstances[renderId].push(instance);
  31535. return this;
  31536. };
  31537. /**
  31538. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31539. * This means the mesh underlying bounding box and sphere are recomputed.
  31540. * Returns the Mesh.
  31541. */
  31542. Mesh.prototype.refreshBoundingInfo = function () {
  31543. return this._refreshBoundingInfo(false);
  31544. };
  31545. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31546. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31547. return this;
  31548. }
  31549. var data = this._getPositionData(applySkeleton);
  31550. if (data) {
  31551. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31552. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31553. }
  31554. if (this.subMeshes) {
  31555. for (var index = 0; index < this.subMeshes.length; index++) {
  31556. this.subMeshes[index].refreshBoundingInfo();
  31557. }
  31558. }
  31559. this._updateBoundingInfo();
  31560. return this;
  31561. };
  31562. Mesh.prototype._getPositionData = function (applySkeleton) {
  31563. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31564. if (data && applySkeleton && this.skeleton) {
  31565. data = BABYLON.Tools.Slice(data);
  31566. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31567. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31568. if (matricesWeightsData && matricesIndicesData) {
  31569. var needExtras = this.numBoneInfluencers > 4;
  31570. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31571. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31572. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31573. var tempVector = BABYLON.Tmp.Vector3[0];
  31574. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31575. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31576. var matWeightIdx = 0;
  31577. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31578. finalMatrix.reset();
  31579. var inf;
  31580. var weight;
  31581. for (inf = 0; inf < 4; inf++) {
  31582. weight = matricesWeightsData[matWeightIdx + inf];
  31583. if (weight > 0) {
  31584. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31585. finalMatrix.addToSelf(tempMatrix);
  31586. }
  31587. }
  31588. if (needExtras) {
  31589. for (inf = 0; inf < 4; inf++) {
  31590. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31591. if (weight > 0) {
  31592. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31593. finalMatrix.addToSelf(tempMatrix);
  31594. }
  31595. }
  31596. }
  31597. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31598. tempVector.toArray(data, index);
  31599. }
  31600. }
  31601. }
  31602. return data;
  31603. };
  31604. Mesh.prototype._createGlobalSubMesh = function (force) {
  31605. var totalVertices = this.getTotalVertices();
  31606. if (!totalVertices || !this.getIndices()) {
  31607. return null;
  31608. }
  31609. // Check if we need to recreate the submeshes
  31610. if (this.subMeshes && this.subMeshes.length > 0) {
  31611. var ib = this.getIndices();
  31612. if (!ib) {
  31613. return null;
  31614. }
  31615. var totalIndices = ib.length;
  31616. var needToRecreate = false;
  31617. if (force) {
  31618. needToRecreate = true;
  31619. }
  31620. else {
  31621. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31622. var submesh = _a[_i];
  31623. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31624. needToRecreate = true;
  31625. break;
  31626. }
  31627. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31628. needToRecreate = true;
  31629. break;
  31630. }
  31631. }
  31632. }
  31633. if (!needToRecreate) {
  31634. return this.subMeshes[0];
  31635. }
  31636. }
  31637. this.releaseSubMeshes();
  31638. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31639. };
  31640. Mesh.prototype.subdivide = function (count) {
  31641. if (count < 1) {
  31642. return;
  31643. }
  31644. var totalIndices = this.getTotalIndices();
  31645. var subdivisionSize = (totalIndices / count) | 0;
  31646. var offset = 0;
  31647. // Ensure that subdivisionSize is a multiple of 3
  31648. while (subdivisionSize % 3 !== 0) {
  31649. subdivisionSize++;
  31650. }
  31651. this.releaseSubMeshes();
  31652. for (var index = 0; index < count; index++) {
  31653. if (offset >= totalIndices) {
  31654. break;
  31655. }
  31656. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31657. offset += subdivisionSize;
  31658. }
  31659. this.synchronizeInstances();
  31660. };
  31661. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31662. if (updatable === void 0) { updatable = false; }
  31663. if (!this._geometry) {
  31664. var vertexData = new BABYLON.VertexData();
  31665. vertexData.set(data, kind);
  31666. var scene = this.getScene();
  31667. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31668. }
  31669. else {
  31670. this._geometry.setVerticesData(kind, data, updatable, stride);
  31671. }
  31672. return this;
  31673. };
  31674. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31675. if (updatable === void 0) { updatable = true; }
  31676. var vb = this.getVertexBuffer(kind);
  31677. if (!vb || vb.isUpdatable() === updatable) {
  31678. return;
  31679. }
  31680. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31681. };
  31682. /**
  31683. * Sets the mesh VertexBuffer.
  31684. * Returns the Mesh.
  31685. */
  31686. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31687. if (!this._geometry) {
  31688. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31689. }
  31690. this._geometry.setVerticesBuffer(buffer);
  31691. return this;
  31692. };
  31693. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31694. if (!this._geometry) {
  31695. return this;
  31696. }
  31697. if (!makeItUnique) {
  31698. this._geometry.updateVerticesData(kind, data, updateExtends);
  31699. }
  31700. else {
  31701. this.makeGeometryUnique();
  31702. this.updateVerticesData(kind, data, updateExtends, false);
  31703. }
  31704. return this;
  31705. };
  31706. /**
  31707. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31708. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31709. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31710. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31711. * Returns the Mesh.
  31712. */
  31713. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31714. if (computeNormals === void 0) { computeNormals = true; }
  31715. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31716. if (!positions) {
  31717. return this;
  31718. }
  31719. positionFunction(positions);
  31720. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31721. if (computeNormals) {
  31722. var indices = this.getIndices();
  31723. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31724. if (!normals) {
  31725. return this;
  31726. }
  31727. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31728. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31729. }
  31730. return this;
  31731. };
  31732. /**
  31733. * Creates a un-shared specific occurence of the geometry for the mesh.
  31734. * Returns the Mesh.
  31735. */
  31736. Mesh.prototype.makeGeometryUnique = function () {
  31737. if (!this._geometry) {
  31738. return this;
  31739. }
  31740. var oldGeometry = this._geometry;
  31741. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31742. oldGeometry.releaseForMesh(this, true);
  31743. geometry.applyToMesh(this);
  31744. return this;
  31745. };
  31746. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31747. if (totalVertices === void 0) { totalVertices = null; }
  31748. if (updatable === void 0) { updatable = false; }
  31749. if (!this._geometry) {
  31750. var vertexData = new BABYLON.VertexData();
  31751. vertexData.indices = indices;
  31752. var scene = this.getScene();
  31753. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31754. }
  31755. else {
  31756. this._geometry.setIndices(indices, totalVertices, updatable);
  31757. }
  31758. return this;
  31759. };
  31760. /**
  31761. * Update the current index buffer
  31762. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31763. * Returns the Mesh.
  31764. */
  31765. Mesh.prototype.updateIndices = function (indices, offset) {
  31766. if (!this._geometry) {
  31767. return this;
  31768. }
  31769. this._geometry.updateIndices(indices, offset);
  31770. return this;
  31771. };
  31772. /**
  31773. * Invert the geometry to move from a right handed system to a left handed one.
  31774. * Returns the Mesh.
  31775. */
  31776. Mesh.prototype.toLeftHanded = function () {
  31777. if (!this._geometry) {
  31778. return this;
  31779. }
  31780. this._geometry.toLeftHanded();
  31781. return this;
  31782. };
  31783. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31784. if (!this._geometry) {
  31785. return this;
  31786. }
  31787. var engine = this.getScene().getEngine();
  31788. // Wireframe
  31789. var indexToBind;
  31790. if (this._unIndexed) {
  31791. indexToBind = null;
  31792. }
  31793. else {
  31794. switch (fillMode) {
  31795. case BABYLON.Material.PointFillMode:
  31796. indexToBind = null;
  31797. break;
  31798. case BABYLON.Material.WireFrameFillMode:
  31799. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31800. break;
  31801. default:
  31802. case BABYLON.Material.TriangleFillMode:
  31803. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31804. break;
  31805. }
  31806. }
  31807. // VBOs
  31808. this._geometry._bind(effect, indexToBind);
  31809. return this;
  31810. };
  31811. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31812. if (alternate === void 0) { alternate = false; }
  31813. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31814. return this;
  31815. }
  31816. this.onBeforeDrawObservable.notifyObservers(this);
  31817. var scene = this.getScene();
  31818. var engine = scene.getEngine();
  31819. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31820. // or triangles as points
  31821. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31822. }
  31823. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31824. // Triangles as wireframe
  31825. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31826. }
  31827. else {
  31828. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31829. }
  31830. if (scene._isAlternateRenderingEnabled && !alternate) {
  31831. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31832. if (!effect || !scene.activeCamera) {
  31833. return this;
  31834. }
  31835. scene._switchToAlternateCameraConfiguration(true);
  31836. this._effectiveMaterial.bindView(effect);
  31837. this._effectiveMaterial.bindViewProjection(effect);
  31838. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31839. this._draw(subMesh, fillMode, instancesCount, true);
  31840. engine.setViewport(scene.activeCamera.viewport);
  31841. scene._switchToAlternateCameraConfiguration(false);
  31842. this._effectiveMaterial.bindView(effect);
  31843. this._effectiveMaterial.bindViewProjection(effect);
  31844. }
  31845. return this;
  31846. };
  31847. /**
  31848. * Registers for this mesh a javascript function called just before the rendering process.
  31849. * This function is passed the current mesh.
  31850. * Return the Mesh.
  31851. */
  31852. Mesh.prototype.registerBeforeRender = function (func) {
  31853. this.onBeforeRenderObservable.add(func);
  31854. return this;
  31855. };
  31856. /**
  31857. * Disposes a previously registered javascript function called before the rendering.
  31858. * This function is passed the current mesh.
  31859. * Returns the Mesh.
  31860. */
  31861. Mesh.prototype.unregisterBeforeRender = function (func) {
  31862. this.onBeforeRenderObservable.removeCallback(func);
  31863. return this;
  31864. };
  31865. /**
  31866. * Registers for this mesh a javascript function called just after the rendering is complete.
  31867. * This function is passed the current mesh.
  31868. * Returns the Mesh.
  31869. */
  31870. Mesh.prototype.registerAfterRender = function (func) {
  31871. this.onAfterRenderObservable.add(func);
  31872. return this;
  31873. };
  31874. /**
  31875. * Disposes a previously registered javascript function called after the rendering.
  31876. * This function is passed the current mesh.
  31877. * Return the Mesh.
  31878. */
  31879. Mesh.prototype.unregisterAfterRender = function (func) {
  31880. this.onAfterRenderObservable.removeCallback(func);
  31881. return this;
  31882. };
  31883. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31884. var scene = this.getScene();
  31885. this._batchCache.mustReturn = false;
  31886. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31887. this._batchCache.visibleInstances[subMeshId] = null;
  31888. if (this._visibleInstances) {
  31889. var currentRenderId = scene.getRenderId();
  31890. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31891. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31892. var selfRenderId = this._renderId;
  31893. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31894. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31895. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31896. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31897. }
  31898. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31899. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31900. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31901. this._batchCache.mustReturn = true;
  31902. return this._batchCache;
  31903. }
  31904. if (currentRenderId !== selfRenderId) {
  31905. this._batchCache.renderSelf[subMeshId] = false;
  31906. }
  31907. }
  31908. this._renderIdForInstances[subMeshId] = currentRenderId;
  31909. }
  31910. return this._batchCache;
  31911. };
  31912. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31913. var visibleInstances = batch.visibleInstances[subMesh._id];
  31914. if (!visibleInstances) {
  31915. return this;
  31916. }
  31917. var matricesCount = visibleInstances.length + 1;
  31918. var bufferSize = matricesCount * 16 * 4;
  31919. var currentInstancesBufferSize = this._instancesBufferSize;
  31920. var instancesBuffer = this._instancesBuffer;
  31921. while (this._instancesBufferSize < bufferSize) {
  31922. this._instancesBufferSize *= 2;
  31923. }
  31924. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31925. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31926. }
  31927. var offset = 0;
  31928. var instancesCount = 0;
  31929. var world = this.getWorldMatrix();
  31930. if (batch.renderSelf[subMesh._id]) {
  31931. world.copyToArray(this._instancesData, offset);
  31932. offset += 16;
  31933. instancesCount++;
  31934. }
  31935. if (visibleInstances) {
  31936. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31937. var instance = visibleInstances[instanceIndex];
  31938. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31939. offset += 16;
  31940. instancesCount++;
  31941. }
  31942. }
  31943. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31944. if (instancesBuffer) {
  31945. instancesBuffer.dispose();
  31946. }
  31947. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31948. this._instancesBuffer = instancesBuffer;
  31949. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31950. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31951. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31952. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31953. }
  31954. else {
  31955. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31956. }
  31957. this._bind(subMesh, effect, fillMode);
  31958. this._draw(subMesh, fillMode, instancesCount);
  31959. engine.unbindInstanceAttributes();
  31960. return this;
  31961. };
  31962. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31963. var scene = this.getScene();
  31964. var engine = scene.getEngine();
  31965. if (hardwareInstancedRendering) {
  31966. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31967. }
  31968. else {
  31969. if (batch.renderSelf[subMesh._id]) {
  31970. // Draw
  31971. if (onBeforeDraw) {
  31972. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31973. }
  31974. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31975. }
  31976. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31977. if (visibleInstancesForSubMesh) {
  31978. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31979. var instance = visibleInstancesForSubMesh[instanceIndex];
  31980. // World
  31981. var world = instance.getWorldMatrix();
  31982. if (onBeforeDraw) {
  31983. onBeforeDraw(true, world, effectiveMaterial);
  31984. }
  31985. // Draw
  31986. this._draw(subMesh, fillMode);
  31987. }
  31988. }
  31989. }
  31990. return this;
  31991. };
  31992. /**
  31993. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  31994. * @param subMesh defines the subMesh to render
  31995. * @param enableAlphaMode defines if alpha mode can be changed
  31996. * @returns the current mesh
  31997. */
  31998. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31999. this._checkOcclusionQuery();
  32000. if (this._isOccluded) {
  32001. return this;
  32002. }
  32003. var scene = this.getScene();
  32004. // Managing instances
  32005. var batch = this._getInstancesRenderList(subMesh._id);
  32006. if (batch.mustReturn) {
  32007. return this;
  32008. }
  32009. // Checking geometry state
  32010. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32011. return this;
  32012. }
  32013. this.onBeforeRenderObservable.notifyObservers(this);
  32014. var engine = scene.getEngine();
  32015. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32016. // Material
  32017. var material = subMesh.getMaterial();
  32018. if (!material) {
  32019. return this;
  32020. }
  32021. this._effectiveMaterial = material;
  32022. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32023. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32024. return this;
  32025. }
  32026. }
  32027. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32028. return this;
  32029. }
  32030. // Alpha mode
  32031. if (enableAlphaMode) {
  32032. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32033. }
  32034. // Outline - step 1
  32035. var savedDepthWrite = engine.getDepthWrite();
  32036. if (this.renderOutline) {
  32037. engine.setDepthWrite(false);
  32038. scene.getOutlineRenderer().render(subMesh, batch);
  32039. engine.setDepthWrite(savedDepthWrite);
  32040. }
  32041. var effect;
  32042. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32043. effect = subMesh.effect;
  32044. }
  32045. else {
  32046. effect = this._effectiveMaterial.getEffect();
  32047. }
  32048. if (!effect) {
  32049. return this;
  32050. }
  32051. var sideOrientation = this.overrideMaterialSideOrientation;
  32052. if (sideOrientation == null) {
  32053. sideOrientation = this._effectiveMaterial.sideOrientation;
  32054. if (this._getWorldMatrixDeterminant() < 0) {
  32055. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32056. }
  32057. }
  32058. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32059. if (this._effectiveMaterial.forceDepthWrite) {
  32060. engine.setDepthWrite(true);
  32061. }
  32062. // Bind
  32063. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32064. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32065. this._bind(subMesh, effect, fillMode);
  32066. }
  32067. var world = this.getWorldMatrix();
  32068. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32069. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32070. }
  32071. else {
  32072. this._effectiveMaterial.bind(world, this);
  32073. }
  32074. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32075. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32076. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32077. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32078. }
  32079. // Draw
  32080. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32081. // Unbind
  32082. this._effectiveMaterial.unbind();
  32083. // Outline - step 2
  32084. if (this.renderOutline && savedDepthWrite) {
  32085. engine.setDepthWrite(true);
  32086. engine.setColorWrite(false);
  32087. scene.getOutlineRenderer().render(subMesh, batch);
  32088. engine.setColorWrite(true);
  32089. }
  32090. // Overlay
  32091. if (this.renderOverlay) {
  32092. var currentMode = engine.getAlphaMode();
  32093. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32094. scene.getOutlineRenderer().render(subMesh, batch, true);
  32095. engine.setAlphaMode(currentMode);
  32096. }
  32097. this.onAfterRenderObservable.notifyObservers(this);
  32098. return this;
  32099. };
  32100. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32101. if (isInstance && effectiveMaterial) {
  32102. effectiveMaterial.bindOnlyWorldMatrix(world);
  32103. }
  32104. };
  32105. /**
  32106. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32107. */
  32108. Mesh.prototype.getEmittedParticleSystems = function () {
  32109. var results = new Array();
  32110. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32111. var particleSystem = this.getScene().particleSystems[index];
  32112. if (particleSystem.emitter === this) {
  32113. results.push(particleSystem);
  32114. }
  32115. }
  32116. return results;
  32117. };
  32118. /**
  32119. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32120. */
  32121. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32122. var results = new Array();
  32123. var descendants = this.getDescendants();
  32124. descendants.push(this);
  32125. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32126. var particleSystem = this.getScene().particleSystems[index];
  32127. var emitter = particleSystem.emitter;
  32128. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32129. results.push(particleSystem);
  32130. }
  32131. }
  32132. return results;
  32133. };
  32134. /**
  32135. * Normalize matrix weights so that all vertices have a total weight set to 1
  32136. */
  32137. Mesh.prototype.cleanMatrixWeights = function () {
  32138. var epsilon = 1e-3;
  32139. var noInfluenceBoneIndex = 0.0;
  32140. if (this.skeleton) {
  32141. noInfluenceBoneIndex = this.skeleton.bones.length;
  32142. }
  32143. else {
  32144. return;
  32145. }
  32146. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32147. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32148. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32149. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32150. var influencers = this.numBoneInfluencers;
  32151. var size = matricesWeights.length;
  32152. for (var i = 0; i < size; i += 4) {
  32153. var weight = 0.0;
  32154. var firstZeroWeight = -1;
  32155. for (var j = 0; j < 4; j++) {
  32156. var w = matricesWeights[i + j];
  32157. weight += w;
  32158. if (w < epsilon && firstZeroWeight < 0) {
  32159. firstZeroWeight = j;
  32160. }
  32161. }
  32162. if (matricesWeightsExtra) {
  32163. for (var j = 0; j < 4; j++) {
  32164. var w = matricesWeightsExtra[i + j];
  32165. weight += w;
  32166. if (w < epsilon && firstZeroWeight < 0) {
  32167. firstZeroWeight = j + 4;
  32168. }
  32169. }
  32170. }
  32171. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32172. firstZeroWeight = influencers - 1;
  32173. }
  32174. if (weight > epsilon) {
  32175. var mweight = 1.0 / weight;
  32176. for (var j = 0; j < 4; j++) {
  32177. matricesWeights[i + j] *= mweight;
  32178. }
  32179. if (matricesWeightsExtra) {
  32180. for (var j = 0; j < 4; j++) {
  32181. matricesWeightsExtra[i + j] *= mweight;
  32182. }
  32183. }
  32184. }
  32185. else {
  32186. if (firstZeroWeight >= 4) {
  32187. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32188. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32189. }
  32190. else {
  32191. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32192. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32193. }
  32194. }
  32195. }
  32196. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32197. if (matricesIndicesExtra) {
  32198. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32199. }
  32200. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32201. if (matricesWeightsExtra) {
  32202. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32203. }
  32204. };
  32205. Mesh.prototype._checkDelayState = function () {
  32206. var scene = this.getScene();
  32207. if (this._geometry) {
  32208. this._geometry.load(scene);
  32209. }
  32210. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32211. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32212. this._queueLoad(scene);
  32213. }
  32214. return this;
  32215. };
  32216. Mesh.prototype._queueLoad = function (scene) {
  32217. var _this = this;
  32218. scene._addPendingData(this);
  32219. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32220. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32221. if (data instanceof ArrayBuffer) {
  32222. _this._delayLoadingFunction(data, _this);
  32223. }
  32224. else {
  32225. _this._delayLoadingFunction(JSON.parse(data), _this);
  32226. }
  32227. _this.instances.forEach(function (instance) {
  32228. instance._syncSubMeshes();
  32229. });
  32230. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32231. scene._removePendingData(_this);
  32232. }, function () { }, scene.database, getBinaryData);
  32233. return this;
  32234. };
  32235. /**
  32236. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32237. */
  32238. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32239. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32240. return false;
  32241. }
  32242. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32243. return false;
  32244. }
  32245. this._checkDelayState();
  32246. return true;
  32247. };
  32248. /**
  32249. * Sets the mesh material by the material or multiMaterial `id` property.
  32250. * The material `id` is a string identifying the material or the multiMaterial.
  32251. * This method returns the Mesh.
  32252. */
  32253. Mesh.prototype.setMaterialByID = function (id) {
  32254. var materials = this.getScene().materials;
  32255. var index;
  32256. for (index = materials.length - 1; index > -1; index--) {
  32257. if (materials[index].id === id) {
  32258. this.material = materials[index];
  32259. return this;
  32260. }
  32261. }
  32262. // Multi
  32263. var multiMaterials = this.getScene().multiMaterials;
  32264. for (index = multiMaterials.length - 1; index > -1; index--) {
  32265. if (multiMaterials[index].id === id) {
  32266. this.material = multiMaterials[index];
  32267. return this;
  32268. }
  32269. }
  32270. return this;
  32271. };
  32272. /**
  32273. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32274. */
  32275. Mesh.prototype.getAnimatables = function () {
  32276. var results = new Array();
  32277. if (this.material) {
  32278. results.push(this.material);
  32279. }
  32280. if (this.skeleton) {
  32281. results.push(this.skeleton);
  32282. }
  32283. return results;
  32284. };
  32285. /**
  32286. * Modifies the mesh geometry according to the passed transformation matrix.
  32287. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32288. * The mesh normals are modified accordingly the same transformation.
  32289. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32290. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32291. * Returns the Mesh.
  32292. */
  32293. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32294. // Position
  32295. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32296. return this;
  32297. }
  32298. var submeshes = this.subMeshes.splice(0);
  32299. this._resetPointsArrayCache();
  32300. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32301. var temp = new Array();
  32302. var index;
  32303. for (index = 0; index < data.length; index += 3) {
  32304. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32305. }
  32306. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32307. // Normals
  32308. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32309. return this;
  32310. }
  32311. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32312. temp = [];
  32313. for (index = 0; index < data.length; index += 3) {
  32314. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32315. }
  32316. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32317. // flip faces?
  32318. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32319. this.flipFaces();
  32320. }
  32321. // Restore submeshes
  32322. this.releaseSubMeshes();
  32323. this.subMeshes = submeshes;
  32324. return this;
  32325. };
  32326. /**
  32327. * Modifies the mesh geometry according to its own current World Matrix.
  32328. * The mesh World Matrix is then reset.
  32329. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32330. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32331. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32332. * Returns the Mesh.
  32333. */
  32334. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32335. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32336. this.scaling.copyFromFloats(1, 1, 1);
  32337. this.position.copyFromFloats(0, 0, 0);
  32338. this.rotation.copyFromFloats(0, 0, 0);
  32339. //only if quaternion is already set
  32340. if (this.rotationQuaternion) {
  32341. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32342. }
  32343. this._worldMatrix = BABYLON.Matrix.Identity();
  32344. return this;
  32345. };
  32346. Object.defineProperty(Mesh.prototype, "_positions", {
  32347. // Cache
  32348. get: function () {
  32349. if (this._geometry) {
  32350. return this._geometry._positions;
  32351. }
  32352. return null;
  32353. },
  32354. enumerable: true,
  32355. configurable: true
  32356. });
  32357. Mesh.prototype._resetPointsArrayCache = function () {
  32358. if (this._geometry) {
  32359. this._geometry._resetPointsArrayCache();
  32360. }
  32361. return this;
  32362. };
  32363. Mesh.prototype._generatePointsArray = function () {
  32364. if (this._geometry) {
  32365. return this._geometry._generatePointsArray();
  32366. }
  32367. return false;
  32368. };
  32369. /**
  32370. * Returns a new Mesh object generated from the current mesh properties.
  32371. * This method must not get confused with createInstance().
  32372. * The parameter `name` is a string, the name given to the new mesh.
  32373. * The optional parameter `newParent` can be any Node object (default `null`).
  32374. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32375. * 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.
  32376. */
  32377. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32378. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32379. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32380. };
  32381. /**
  32382. * Releases resources associated with this mesh.
  32383. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32384. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32385. */
  32386. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32387. var _this = this;
  32388. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32389. this.morphTargetManager = null;
  32390. if (this._geometry) {
  32391. this._geometry.releaseForMesh(this, true);
  32392. }
  32393. // Sources
  32394. var meshes = this.getScene().meshes;
  32395. meshes.forEach(function (abstractMesh) {
  32396. var mesh = abstractMesh;
  32397. if (mesh._source && mesh._source === _this) {
  32398. mesh._source = null;
  32399. }
  32400. });
  32401. this._source = null;
  32402. // Instances
  32403. if (this._instancesBuffer) {
  32404. this._instancesBuffer.dispose();
  32405. this._instancesBuffer = null;
  32406. }
  32407. while (this.instances.length) {
  32408. this.instances[0].dispose();
  32409. }
  32410. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32411. };
  32412. /**
  32413. * Modifies the mesh geometry according to a displacement map.
  32414. * 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.
  32415. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32416. * This method returns nothing.
  32417. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32418. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32419. * 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.
  32420. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32421. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32422. *
  32423. * Returns the Mesh.
  32424. */
  32425. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32426. var _this = this;
  32427. var scene = this.getScene();
  32428. var onload = function (img) {
  32429. // Getting height map data
  32430. var canvas = document.createElement("canvas");
  32431. var context = canvas.getContext("2d");
  32432. var heightMapWidth = img.width;
  32433. var heightMapHeight = img.height;
  32434. canvas.width = heightMapWidth;
  32435. canvas.height = heightMapHeight;
  32436. context.drawImage(img, 0, 0);
  32437. // Create VertexData from map data
  32438. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32439. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32440. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32441. //execute success callback, if set
  32442. if (onSuccess) {
  32443. onSuccess(_this);
  32444. }
  32445. };
  32446. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32447. return this;
  32448. };
  32449. /**
  32450. * Modifies the mesh geometry according to a displacementMap buffer.
  32451. * 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.
  32452. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32453. * This method returns nothing.
  32454. * 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.
  32455. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32456. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32457. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32458. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32459. *
  32460. * Returns the Mesh.
  32461. */
  32462. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32463. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32464. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32465. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32466. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32467. return this;
  32468. }
  32469. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32470. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32471. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32472. var position = BABYLON.Vector3.Zero();
  32473. var normal = BABYLON.Vector3.Zero();
  32474. var uv = BABYLON.Vector2.Zero();
  32475. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32476. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32477. for (var index = 0; index < positions.length; index += 3) {
  32478. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32479. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32480. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32481. // Compute height
  32482. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32483. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32484. var pos = (u + v * heightMapWidth) * 4;
  32485. var r = buffer[pos] / 255.0;
  32486. var g = buffer[pos + 1] / 255.0;
  32487. var b = buffer[pos + 2] / 255.0;
  32488. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32489. normal.normalize();
  32490. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32491. position = position.add(normal);
  32492. position.toArray(positions, index);
  32493. }
  32494. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32495. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32496. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32497. return this;
  32498. };
  32499. /**
  32500. * Modify the mesh to get a flat shading rendering.
  32501. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32502. * This method returns the Mesh.
  32503. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32504. */
  32505. Mesh.prototype.convertToFlatShadedMesh = function () {
  32506. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32507. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32508. var kinds = this.getVerticesDataKinds();
  32509. var vbs = {};
  32510. var data = {};
  32511. var newdata = {};
  32512. var updatableNormals = false;
  32513. var kindIndex;
  32514. var kind;
  32515. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32516. kind = kinds[kindIndex];
  32517. var vertexBuffer = this.getVertexBuffer(kind);
  32518. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32519. updatableNormals = vertexBuffer.isUpdatable();
  32520. kinds.splice(kindIndex, 1);
  32521. kindIndex--;
  32522. continue;
  32523. }
  32524. vbs[kind] = vertexBuffer;
  32525. data[kind] = vbs[kind].getData();
  32526. newdata[kind] = [];
  32527. }
  32528. // Save previous submeshes
  32529. var previousSubmeshes = this.subMeshes.slice(0);
  32530. var indices = this.getIndices();
  32531. var totalIndices = this.getTotalIndices();
  32532. // Generating unique vertices per face
  32533. var index;
  32534. for (index = 0; index < totalIndices; index++) {
  32535. var vertexIndex = indices[index];
  32536. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32537. kind = kinds[kindIndex];
  32538. var stride = vbs[kind].getStrideSize();
  32539. for (var offset = 0; offset < stride; offset++) {
  32540. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32541. }
  32542. }
  32543. }
  32544. // Updating faces & normal
  32545. var normals = [];
  32546. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32547. for (index = 0; index < totalIndices; index += 3) {
  32548. indices[index] = index;
  32549. indices[index + 1] = index + 1;
  32550. indices[index + 2] = index + 2;
  32551. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32552. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32553. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32554. var p1p2 = p1.subtract(p2);
  32555. var p3p2 = p3.subtract(p2);
  32556. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32557. // Store same normals for every vertex
  32558. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32559. normals.push(normal.x);
  32560. normals.push(normal.y);
  32561. normals.push(normal.z);
  32562. }
  32563. }
  32564. this.setIndices(indices);
  32565. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32566. // Updating vertex buffers
  32567. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32568. kind = kinds[kindIndex];
  32569. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32570. }
  32571. // Updating submeshes
  32572. this.releaseSubMeshes();
  32573. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32574. var previousOne = previousSubmeshes[submeshIndex];
  32575. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32576. }
  32577. this.synchronizeInstances();
  32578. return this;
  32579. };
  32580. /**
  32581. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32582. * In other words, more vertices, no more indices and a single bigger VBO.
  32583. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32584. * Returns the Mesh.
  32585. */
  32586. Mesh.prototype.convertToUnIndexedMesh = function () {
  32587. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32588. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32589. var kinds = this.getVerticesDataKinds();
  32590. var vbs = {};
  32591. var data = {};
  32592. var newdata = {};
  32593. var kindIndex;
  32594. var kind;
  32595. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32596. kind = kinds[kindIndex];
  32597. var vertexBuffer = this.getVertexBuffer(kind);
  32598. vbs[kind] = vertexBuffer;
  32599. data[kind] = vbs[kind].getData();
  32600. newdata[kind] = [];
  32601. }
  32602. // Save previous submeshes
  32603. var previousSubmeshes = this.subMeshes.slice(0);
  32604. var indices = this.getIndices();
  32605. var totalIndices = this.getTotalIndices();
  32606. // Generating unique vertices per face
  32607. var index;
  32608. for (index = 0; index < totalIndices; index++) {
  32609. var vertexIndex = indices[index];
  32610. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32611. kind = kinds[kindIndex];
  32612. var stride = vbs[kind].getStrideSize();
  32613. for (var offset = 0; offset < stride; offset++) {
  32614. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32615. }
  32616. }
  32617. }
  32618. // Updating indices
  32619. for (index = 0; index < totalIndices; index += 3) {
  32620. indices[index] = index;
  32621. indices[index + 1] = index + 1;
  32622. indices[index + 2] = index + 2;
  32623. }
  32624. this.setIndices(indices);
  32625. // Updating vertex buffers
  32626. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32627. kind = kinds[kindIndex];
  32628. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32629. }
  32630. // Updating submeshes
  32631. this.releaseSubMeshes();
  32632. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32633. var previousOne = previousSubmeshes[submeshIndex];
  32634. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32635. }
  32636. this._unIndexed = true;
  32637. this.synchronizeInstances();
  32638. return this;
  32639. };
  32640. /**
  32641. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32642. * This method returns the Mesh.
  32643. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32644. */
  32645. Mesh.prototype.flipFaces = function (flipNormals) {
  32646. if (flipNormals === void 0) { flipNormals = false; }
  32647. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32648. var i;
  32649. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32650. for (i = 0; i < vertex_data.normals.length; i++) {
  32651. vertex_data.normals[i] *= -1;
  32652. }
  32653. }
  32654. if (vertex_data.indices) {
  32655. var temp;
  32656. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32657. // reassign indices
  32658. temp = vertex_data.indices[i + 1];
  32659. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32660. vertex_data.indices[i + 2] = temp;
  32661. }
  32662. }
  32663. vertex_data.applyToMesh(this);
  32664. return this;
  32665. };
  32666. // Instances
  32667. /**
  32668. * Creates a new InstancedMesh object from the mesh model.
  32669. * An instance shares the same properties and the same material than its model.
  32670. * Only these properties of each instance can then be set individually :
  32671. * - position
  32672. * - rotation
  32673. * - rotationQuaternion
  32674. * - setPivotMatrix
  32675. * - scaling
  32676. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32677. * Warning : this method is not supported for Line mesh and LineSystem
  32678. */
  32679. Mesh.prototype.createInstance = function (name) {
  32680. return new BABYLON.InstancedMesh(name, this);
  32681. };
  32682. /**
  32683. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32684. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32685. * This method returns the Mesh.
  32686. */
  32687. Mesh.prototype.synchronizeInstances = function () {
  32688. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32689. var instance = this.instances[instanceIndex];
  32690. instance._syncSubMeshes();
  32691. }
  32692. return this;
  32693. };
  32694. /**
  32695. * Simplify the mesh according to the given array of settings.
  32696. * Function will return immediately and will simplify async. It returns the Mesh.
  32697. * @param settings a collection of simplification settings.
  32698. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32699. * @param type the type of simplification to run.
  32700. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32701. */
  32702. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32703. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32704. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32705. this.getScene().simplificationQueue.addTask({
  32706. settings: settings,
  32707. parallelProcessing: parallelProcessing,
  32708. mesh: this,
  32709. simplificationType: simplificationType,
  32710. successCallback: successCallback
  32711. });
  32712. return this;
  32713. };
  32714. /**
  32715. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32716. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32717. * This should be used together with the simplification to avoid disappearing triangles.
  32718. * Returns the Mesh.
  32719. * @param successCallback an optional success callback to be called after the optimization finished.
  32720. */
  32721. Mesh.prototype.optimizeIndices = function (successCallback) {
  32722. var _this = this;
  32723. var indices = this.getIndices();
  32724. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32725. if (!positions || !indices) {
  32726. return this;
  32727. }
  32728. var vectorPositions = new Array();
  32729. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32730. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32731. }
  32732. var dupes = new Array();
  32733. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32734. var realPos = vectorPositions.length - 1 - iteration;
  32735. var testedPosition = vectorPositions[realPos];
  32736. for (var j = 0; j < realPos; ++j) {
  32737. var againstPosition = vectorPositions[j];
  32738. if (testedPosition.equals(againstPosition)) {
  32739. dupes[realPos] = j;
  32740. break;
  32741. }
  32742. }
  32743. }, function () {
  32744. for (var i = 0; i < indices.length; ++i) {
  32745. indices[i] = dupes[indices[i]] || indices[i];
  32746. }
  32747. //indices are now reordered
  32748. var originalSubMeshes = _this.subMeshes.slice(0);
  32749. _this.setIndices(indices);
  32750. _this.subMeshes = originalSubMeshes;
  32751. if (successCallback) {
  32752. successCallback(_this);
  32753. }
  32754. });
  32755. return this;
  32756. };
  32757. Mesh.prototype.serialize = function (serializationObject) {
  32758. serializationObject.name = this.name;
  32759. serializationObject.id = this.id;
  32760. serializationObject.type = this.getClassName();
  32761. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32762. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32763. }
  32764. serializationObject.position = this.position.asArray();
  32765. if (this.rotationQuaternion) {
  32766. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32767. }
  32768. else if (this.rotation) {
  32769. serializationObject.rotation = this.rotation.asArray();
  32770. }
  32771. serializationObject.scaling = this.scaling.asArray();
  32772. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32773. serializationObject.isEnabled = this.isEnabled(false);
  32774. serializationObject.isVisible = this.isVisible;
  32775. serializationObject.infiniteDistance = this.infiniteDistance;
  32776. serializationObject.pickable = this.isPickable;
  32777. serializationObject.receiveShadows = this.receiveShadows;
  32778. serializationObject.billboardMode = this.billboardMode;
  32779. serializationObject.visibility = this.visibility;
  32780. serializationObject.checkCollisions = this.checkCollisions;
  32781. serializationObject.isBlocker = this.isBlocker;
  32782. // Parent
  32783. if (this.parent) {
  32784. serializationObject.parentId = this.parent.id;
  32785. }
  32786. // Geometry
  32787. serializationObject.isUnIndexed = this.isUnIndexed;
  32788. var geometry = this._geometry;
  32789. if (geometry) {
  32790. var geometryId = geometry.id;
  32791. serializationObject.geometryId = geometryId;
  32792. // SubMeshes
  32793. serializationObject.subMeshes = [];
  32794. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32795. var subMesh = this.subMeshes[subIndex];
  32796. serializationObject.subMeshes.push({
  32797. materialIndex: subMesh.materialIndex,
  32798. verticesStart: subMesh.verticesStart,
  32799. verticesCount: subMesh.verticesCount,
  32800. indexStart: subMesh.indexStart,
  32801. indexCount: subMesh.indexCount
  32802. });
  32803. }
  32804. }
  32805. // Material
  32806. if (this.material) {
  32807. serializationObject.materialId = this.material.id;
  32808. }
  32809. else {
  32810. this.material = null;
  32811. }
  32812. // Morph targets
  32813. if (this.morphTargetManager) {
  32814. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32815. }
  32816. // Skeleton
  32817. if (this.skeleton) {
  32818. serializationObject.skeletonId = this.skeleton.id;
  32819. }
  32820. // Physics
  32821. //TODO implement correct serialization for physics impostors.
  32822. var impostor = this.getPhysicsImpostor();
  32823. if (impostor) {
  32824. serializationObject.physicsMass = impostor.getParam("mass");
  32825. serializationObject.physicsFriction = impostor.getParam("friction");
  32826. serializationObject.physicsRestitution = impostor.getParam("mass");
  32827. serializationObject.physicsImpostor = impostor.type;
  32828. }
  32829. // Metadata
  32830. if (this.metadata) {
  32831. serializationObject.metadata = this.metadata;
  32832. }
  32833. // Instances
  32834. serializationObject.instances = [];
  32835. for (var index = 0; index < this.instances.length; index++) {
  32836. var instance = this.instances[index];
  32837. var serializationInstance = {
  32838. name: instance.name,
  32839. id: instance.id,
  32840. position: instance.position.asArray(),
  32841. scaling: instance.scaling.asArray()
  32842. };
  32843. if (instance.rotationQuaternion) {
  32844. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32845. }
  32846. else if (instance.rotation) {
  32847. serializationInstance.rotation = instance.rotation.asArray();
  32848. }
  32849. serializationObject.instances.push(serializationInstance);
  32850. // Animations
  32851. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32852. serializationInstance.ranges = instance.serializeAnimationRanges();
  32853. }
  32854. //
  32855. // Animations
  32856. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32857. serializationObject.ranges = this.serializeAnimationRanges();
  32858. // Layer mask
  32859. serializationObject.layerMask = this.layerMask;
  32860. // Alpha
  32861. serializationObject.alphaIndex = this.alphaIndex;
  32862. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32863. // Overlay
  32864. serializationObject.overlayAlpha = this.overlayAlpha;
  32865. serializationObject.overlayColor = this.overlayColor.asArray();
  32866. serializationObject.renderOverlay = this.renderOverlay;
  32867. // Fog
  32868. serializationObject.applyFog = this.applyFog;
  32869. // Action Manager
  32870. if (this.actionManager) {
  32871. serializationObject.actions = this.actionManager.serialize(this.name);
  32872. }
  32873. };
  32874. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32875. if (!this.geometry) {
  32876. return;
  32877. }
  32878. this._markSubMeshesAsAttributesDirty();
  32879. var morphTargetManager = this._morphTargetManager;
  32880. if (morphTargetManager && morphTargetManager.vertexCount) {
  32881. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32882. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32883. this.morphTargetManager = null;
  32884. return;
  32885. }
  32886. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32887. var morphTarget = morphTargetManager.getActiveTarget(index);
  32888. var positions = morphTarget.getPositions();
  32889. if (!positions) {
  32890. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32891. return;
  32892. }
  32893. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32894. var normals = morphTarget.getNormals();
  32895. if (normals) {
  32896. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32897. }
  32898. var tangents = morphTarget.getTangents();
  32899. if (tangents) {
  32900. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32901. }
  32902. }
  32903. }
  32904. else {
  32905. var index = 0;
  32906. // Positions
  32907. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32908. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32909. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32910. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32911. }
  32912. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32913. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32914. }
  32915. index++;
  32916. }
  32917. }
  32918. };
  32919. // Statics
  32920. /**
  32921. * Returns a new Mesh object parsed from the source provided.
  32922. * The parameter `parsedMesh` is the source.
  32923. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32924. */
  32925. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32926. var mesh;
  32927. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32928. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32929. }
  32930. else {
  32931. mesh = new Mesh(parsedMesh.name, scene);
  32932. }
  32933. mesh.id = parsedMesh.id;
  32934. if (BABYLON.Tags) {
  32935. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32936. }
  32937. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32938. if (parsedMesh.metadata !== undefined) {
  32939. mesh.metadata = parsedMesh.metadata;
  32940. }
  32941. if (parsedMesh.rotationQuaternion) {
  32942. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32943. }
  32944. else if (parsedMesh.rotation) {
  32945. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32946. }
  32947. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32948. if (parsedMesh.localMatrix) {
  32949. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32950. }
  32951. else if (parsedMesh.pivotMatrix) {
  32952. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32953. }
  32954. mesh.setEnabled(parsedMesh.isEnabled);
  32955. mesh.isVisible = parsedMesh.isVisible;
  32956. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32957. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32958. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32959. if (parsedMesh.applyFog !== undefined) {
  32960. mesh.applyFog = parsedMesh.applyFog;
  32961. }
  32962. if (parsedMesh.pickable !== undefined) {
  32963. mesh.isPickable = parsedMesh.pickable;
  32964. }
  32965. if (parsedMesh.alphaIndex !== undefined) {
  32966. mesh.alphaIndex = parsedMesh.alphaIndex;
  32967. }
  32968. mesh.receiveShadows = parsedMesh.receiveShadows;
  32969. mesh.billboardMode = parsedMesh.billboardMode;
  32970. if (parsedMesh.visibility !== undefined) {
  32971. mesh.visibility = parsedMesh.visibility;
  32972. }
  32973. mesh.checkCollisions = parsedMesh.checkCollisions;
  32974. if (parsedMesh.isBlocker !== undefined) {
  32975. mesh.isBlocker = parsedMesh.isBlocker;
  32976. }
  32977. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32978. // freezeWorldMatrix
  32979. if (parsedMesh.freezeWorldMatrix) {
  32980. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32981. }
  32982. // Parent
  32983. if (parsedMesh.parentId) {
  32984. mesh._waitingParentId = parsedMesh.parentId;
  32985. }
  32986. // Actions
  32987. if (parsedMesh.actions !== undefined) {
  32988. mesh._waitingActions = parsedMesh.actions;
  32989. }
  32990. // Overlay
  32991. if (parsedMesh.overlayAlpha !== undefined) {
  32992. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32993. }
  32994. if (parsedMesh.overlayColor !== undefined) {
  32995. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32996. }
  32997. if (parsedMesh.renderOverlay !== undefined) {
  32998. mesh.renderOverlay = parsedMesh.renderOverlay;
  32999. }
  33000. // Geometry
  33001. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33002. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33003. if (parsedMesh.delayLoadingFile) {
  33004. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33005. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33006. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33007. if (parsedMesh._binaryInfo) {
  33008. mesh._binaryInfo = parsedMesh._binaryInfo;
  33009. }
  33010. mesh._delayInfo = [];
  33011. if (parsedMesh.hasUVs) {
  33012. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33013. }
  33014. if (parsedMesh.hasUVs2) {
  33015. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33016. }
  33017. if (parsedMesh.hasUVs3) {
  33018. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33019. }
  33020. if (parsedMesh.hasUVs4) {
  33021. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33022. }
  33023. if (parsedMesh.hasUVs5) {
  33024. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33025. }
  33026. if (parsedMesh.hasUVs6) {
  33027. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33028. }
  33029. if (parsedMesh.hasColors) {
  33030. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33031. }
  33032. if (parsedMesh.hasMatricesIndices) {
  33033. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33034. }
  33035. if (parsedMesh.hasMatricesWeights) {
  33036. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33037. }
  33038. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33039. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33040. mesh._checkDelayState();
  33041. }
  33042. }
  33043. else {
  33044. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33045. }
  33046. // Material
  33047. if (parsedMesh.materialId) {
  33048. mesh.setMaterialByID(parsedMesh.materialId);
  33049. }
  33050. else {
  33051. mesh.material = null;
  33052. }
  33053. // Morph targets
  33054. if (parsedMesh.morphTargetManagerId > -1) {
  33055. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33056. }
  33057. // Skeleton
  33058. if (parsedMesh.skeletonId > -1) {
  33059. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33060. if (parsedMesh.numBoneInfluencers) {
  33061. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33062. }
  33063. }
  33064. // Animations
  33065. if (parsedMesh.animations) {
  33066. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33067. var parsedAnimation = parsedMesh.animations[animationIndex];
  33068. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33069. }
  33070. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33071. }
  33072. if (parsedMesh.autoAnimate) {
  33073. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33074. }
  33075. // Layer Mask
  33076. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33077. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33078. }
  33079. else {
  33080. mesh.layerMask = 0x0FFFFFFF;
  33081. }
  33082. // Physics
  33083. if (parsedMesh.physicsImpostor) {
  33084. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33085. mass: parsedMesh.physicsMass,
  33086. friction: parsedMesh.physicsFriction,
  33087. restitution: parsedMesh.physicsRestitution
  33088. }, scene);
  33089. }
  33090. // Instances
  33091. if (parsedMesh.instances) {
  33092. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33093. var parsedInstance = parsedMesh.instances[index];
  33094. var instance = mesh.createInstance(parsedInstance.name);
  33095. if (parsedInstance.id) {
  33096. instance.id = parsedInstance.id;
  33097. }
  33098. if (BABYLON.Tags) {
  33099. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33100. }
  33101. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33102. if (parsedInstance.parentId) {
  33103. instance._waitingParentId = parsedInstance.parentId;
  33104. }
  33105. if (parsedInstance.rotationQuaternion) {
  33106. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33107. }
  33108. else if (parsedInstance.rotation) {
  33109. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33110. }
  33111. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33112. instance.checkCollisions = mesh.checkCollisions;
  33113. if (parsedMesh.animations) {
  33114. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33115. parsedAnimation = parsedMesh.animations[animationIndex];
  33116. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33117. }
  33118. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33119. if (parsedMesh.autoAnimate) {
  33120. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33121. }
  33122. }
  33123. }
  33124. }
  33125. return mesh;
  33126. };
  33127. /**
  33128. * Creates a ribbon mesh.
  33129. * Please consider using the same method from the MeshBuilder class instead.
  33130. * 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.
  33131. *
  33132. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33133. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33134. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33135. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33136. * 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.
  33137. * 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.
  33138. * 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
  33139. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33140. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33141. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33142. */
  33143. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33144. if (closeArray === void 0) { closeArray = false; }
  33145. if (updatable === void 0) { updatable = false; }
  33146. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33147. pathArray: pathArray,
  33148. closeArray: closeArray,
  33149. closePath: closePath,
  33150. offset: offset,
  33151. updatable: updatable,
  33152. sideOrientation: sideOrientation,
  33153. instance: instance
  33154. }, scene);
  33155. };
  33156. /**
  33157. * Creates a plane polygonal mesh. By default, this is a disc.
  33158. * Please consider using the same method from the MeshBuilder class instead.
  33159. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33160. * 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.
  33161. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33162. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33163. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33164. */
  33165. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33166. if (scene === void 0) { scene = null; }
  33167. var options = {
  33168. radius: radius,
  33169. tessellation: tessellation,
  33170. sideOrientation: sideOrientation,
  33171. updatable: updatable
  33172. };
  33173. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33174. };
  33175. /**
  33176. * Creates a box mesh.
  33177. * Please consider using the same method from the MeshBuilder class instead.
  33178. * The parameter `size` sets the size (float) of each box side (default 1).
  33179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33180. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33182. */
  33183. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33184. if (scene === void 0) { scene = null; }
  33185. var options = {
  33186. size: size,
  33187. sideOrientation: sideOrientation,
  33188. updatable: updatable
  33189. };
  33190. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33191. };
  33192. /**
  33193. * Creates a sphere mesh.
  33194. * Please consider using the same method from the MeshBuilder class instead.
  33195. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33196. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33197. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33198. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33199. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33200. */
  33201. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33202. var options = {
  33203. segments: segments,
  33204. diameterX: diameter,
  33205. diameterY: diameter,
  33206. diameterZ: diameter,
  33207. sideOrientation: sideOrientation,
  33208. updatable: updatable
  33209. };
  33210. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33211. };
  33212. /**
  33213. * Creates a cylinder or a cone mesh.
  33214. * Please consider using the same method from the MeshBuilder class instead.
  33215. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33216. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33217. * 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.
  33218. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33219. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33220. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33221. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33222. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33223. */
  33224. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33225. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33226. if (scene !== undefined) {
  33227. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33228. updatable = scene;
  33229. }
  33230. scene = subdivisions;
  33231. subdivisions = 1;
  33232. }
  33233. var options = {
  33234. height: height,
  33235. diameterTop: diameterTop,
  33236. diameterBottom: diameterBottom,
  33237. tessellation: tessellation,
  33238. subdivisions: subdivisions,
  33239. sideOrientation: sideOrientation,
  33240. updatable: updatable
  33241. };
  33242. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33243. };
  33244. // Torus (Code from SharpDX.org)
  33245. /**
  33246. * Creates a torus mesh.
  33247. * Please consider using the same method from the MeshBuilder class instead.
  33248. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33249. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33250. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33252. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33254. */
  33255. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33256. var options = {
  33257. diameter: diameter,
  33258. thickness: thickness,
  33259. tessellation: tessellation,
  33260. sideOrientation: sideOrientation,
  33261. updatable: updatable
  33262. };
  33263. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33264. };
  33265. /**
  33266. * Creates a torus knot mesh.
  33267. * Please consider using the same method from the MeshBuilder class instead.
  33268. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33269. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33270. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33271. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33272. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33273. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33275. */
  33276. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33277. var options = {
  33278. radius: radius,
  33279. tube: tube,
  33280. radialSegments: radialSegments,
  33281. tubularSegments: tubularSegments,
  33282. p: p,
  33283. q: q,
  33284. sideOrientation: sideOrientation,
  33285. updatable: updatable
  33286. };
  33287. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33288. };
  33289. /**
  33290. * Creates a line mesh.
  33291. * Please consider using the same method from the MeshBuilder class instead.
  33292. * 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.
  33293. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33294. * The parameter `points` is an array successive Vector3.
  33295. * 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
  33296. * When updating an instance, remember that only point positions can change, not the number of points.
  33297. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33298. */
  33299. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33300. if (scene === void 0) { scene = null; }
  33301. if (updatable === void 0) { updatable = false; }
  33302. if (instance === void 0) { instance = null; }
  33303. var options = {
  33304. points: points,
  33305. updatable: updatable,
  33306. instance: instance
  33307. };
  33308. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33309. };
  33310. /**
  33311. * Creates a dashed line mesh.
  33312. * Please consider using the same method from the MeshBuilder class instead.
  33313. * 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.
  33314. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33315. * The parameter `points` is an array successive Vector3.
  33316. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33317. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33318. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33319. * 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
  33320. * When updating an instance, remember that only point positions can change, not the number of points.
  33321. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33322. */
  33323. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33324. if (scene === void 0) { scene = null; }
  33325. var options = {
  33326. points: points,
  33327. dashSize: dashSize,
  33328. gapSize: gapSize,
  33329. dashNb: dashNb,
  33330. updatable: updatable,
  33331. instance: instance
  33332. };
  33333. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33334. };
  33335. /**
  33336. * Creates a polygon mesh.
  33337. * Please consider using the same method from the MeshBuilder class instead.
  33338. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33339. * 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.
  33340. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33342. * Remember you can only change the shape positions, not their number when updating a polygon.
  33343. */
  33344. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33345. var options = {
  33346. shape: shape,
  33347. holes: holes,
  33348. updatable: updatable,
  33349. sideOrientation: sideOrientation
  33350. };
  33351. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33352. };
  33353. /**
  33354. * Creates an extruded polygon mesh, with depth in the Y direction.
  33355. * Please consider using the same method from the MeshBuilder class instead.
  33356. */
  33357. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33358. var options = {
  33359. shape: shape,
  33360. holes: holes,
  33361. depth: depth,
  33362. updatable: updatable,
  33363. sideOrientation: sideOrientation
  33364. };
  33365. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33366. };
  33367. /**
  33368. * Creates an extruded shape mesh.
  33369. * 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.
  33370. * Please consider using the same method from the MeshBuilder class instead.
  33371. *
  33372. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33373. * 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
  33374. * extruded along the Z axis.
  33375. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33376. * 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.
  33377. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33378. * 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
  33379. * 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
  33380. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33381. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33382. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33384. */
  33385. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33386. if (scene === void 0) { scene = null; }
  33387. var options = {
  33388. shape: shape,
  33389. path: path,
  33390. scale: scale,
  33391. rotation: rotation,
  33392. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33393. sideOrientation: sideOrientation,
  33394. instance: instance,
  33395. updatable: updatable
  33396. };
  33397. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33398. };
  33399. /**
  33400. * Creates an custom extruded shape mesh.
  33401. * 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.
  33402. * Please consider using the same method from the MeshBuilder class instead.
  33403. *
  33404. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33405. * 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
  33406. * extruded along the Z axis.
  33407. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33408. * 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
  33409. * and the distance of this point from the begining of the path :
  33410. * ```javascript
  33411. * var rotationFunction = function(i, distance) {
  33412. * // do things
  33413. * return rotationValue; }
  33414. * ```
  33415. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33416. * 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
  33417. * and the distance of this point from the begining of the path :
  33418. * ```javascript
  33419. * var scaleFunction = function(i, distance) {
  33420. * // do things
  33421. * return scaleValue;}
  33422. * ```
  33423. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33424. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33425. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33426. * 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
  33427. * 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
  33428. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33430. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33432. */
  33433. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33434. var options = {
  33435. shape: shape,
  33436. path: path,
  33437. scaleFunction: scaleFunction,
  33438. rotationFunction: rotationFunction,
  33439. ribbonCloseArray: ribbonCloseArray,
  33440. ribbonClosePath: ribbonClosePath,
  33441. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33442. sideOrientation: sideOrientation,
  33443. instance: instance,
  33444. updatable: updatable
  33445. };
  33446. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33447. };
  33448. /**
  33449. * Creates lathe mesh.
  33450. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33451. * Please consider using the same method from the MeshBuilder class instead.
  33452. * 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
  33453. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33454. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33455. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33456. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33457. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33459. */
  33460. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33461. var options = {
  33462. shape: shape,
  33463. radius: radius,
  33464. tessellation: tessellation,
  33465. sideOrientation: sideOrientation,
  33466. updatable: updatable
  33467. };
  33468. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33469. };
  33470. /**
  33471. * Creates a plane mesh.
  33472. * Please consider using the same method from the MeshBuilder class instead.
  33473. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33474. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33475. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33476. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33477. */
  33478. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33479. var options = {
  33480. size: size,
  33481. width: size,
  33482. height: size,
  33483. sideOrientation: sideOrientation,
  33484. updatable: updatable
  33485. };
  33486. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33487. };
  33488. /**
  33489. * Creates a ground mesh.
  33490. * Please consider using the same method from the MeshBuilder class instead.
  33491. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33492. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33494. */
  33495. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33496. var options = {
  33497. width: width,
  33498. height: height,
  33499. subdivisions: subdivisions,
  33500. updatable: updatable
  33501. };
  33502. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33503. };
  33504. /**
  33505. * Creates a tiled ground mesh.
  33506. * Please consider using the same method from the MeshBuilder class instead.
  33507. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33508. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33509. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33510. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33511. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33512. * numbers of subdivisions on the ground width and height of each tile.
  33513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33514. */
  33515. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33516. var options = {
  33517. xmin: xmin,
  33518. zmin: zmin,
  33519. xmax: xmax,
  33520. zmax: zmax,
  33521. subdivisions: subdivisions,
  33522. precision: precision,
  33523. updatable: updatable
  33524. };
  33525. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33526. };
  33527. /**
  33528. * Creates a ground mesh from a height map.
  33529. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33530. * Please consider using the same method from the MeshBuilder class instead.
  33531. * The parameter `url` sets the URL of the height map image resource.
  33532. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33533. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33534. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33535. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33536. * 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).
  33537. * This function is passed the newly built mesh :
  33538. * ```javascript
  33539. * function(mesh) { // do things
  33540. * return; }
  33541. * ```
  33542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33543. */
  33544. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33545. var options = {
  33546. width: width,
  33547. height: height,
  33548. subdivisions: subdivisions,
  33549. minHeight: minHeight,
  33550. maxHeight: maxHeight,
  33551. updatable: updatable,
  33552. onReady: onReady
  33553. };
  33554. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33555. };
  33556. /**
  33557. * Creates a tube mesh.
  33558. * 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.
  33559. * Please consider using the same method from the MeshBuilder class instead.
  33560. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33561. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33562. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33563. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33564. * 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.
  33565. * It must return a radius value (positive float) :
  33566. * ```javascript
  33567. * var radiusFunction = function(i, distance) {
  33568. * // do things
  33569. * return radius; }
  33570. * ```
  33571. * 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
  33572. * 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
  33573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33574. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33576. */
  33577. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33578. var options = {
  33579. path: path,
  33580. radius: radius,
  33581. tessellation: tessellation,
  33582. radiusFunction: radiusFunction,
  33583. arc: 1,
  33584. cap: cap,
  33585. updatable: updatable,
  33586. sideOrientation: sideOrientation,
  33587. instance: instance
  33588. };
  33589. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33590. };
  33591. /**
  33592. * Creates a polyhedron mesh.
  33593. * Please consider using the same method from the MeshBuilder class instead.
  33594. * 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
  33595. * to choose the wanted type.
  33596. * The parameter `size` (positive float, default 1) sets the polygon size.
  33597. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33598. * 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`.
  33599. * 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
  33600. * 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)`).
  33601. * 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
  33602. * 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.
  33603. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33604. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33606. */
  33607. Mesh.CreatePolyhedron = function (name, options, scene) {
  33608. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33609. };
  33610. /**
  33611. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33612. * Please consider using the same method from the MeshBuilder class instead.
  33613. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33614. * 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`).
  33615. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33616. * 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.
  33617. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33618. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33619. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33620. */
  33621. Mesh.CreateIcoSphere = function (name, options, scene) {
  33622. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33623. };
  33624. /**
  33625. * Creates a decal mesh.
  33626. * Please consider using the same method from the MeshBuilder class instead.
  33627. * 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.
  33628. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33629. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33630. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33631. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33632. */
  33633. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33634. var options = {
  33635. position: position,
  33636. normal: normal,
  33637. size: size,
  33638. angle: angle
  33639. };
  33640. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33641. };
  33642. // Skeletons
  33643. /**
  33644. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33645. */
  33646. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33647. if (!this._sourcePositions) {
  33648. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33649. if (!source) {
  33650. return this._sourcePositions;
  33651. }
  33652. this._sourcePositions = new Float32Array(source);
  33653. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33654. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33655. }
  33656. }
  33657. return this._sourcePositions;
  33658. };
  33659. /**
  33660. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33661. */
  33662. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33663. if (!this._sourceNormals) {
  33664. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33665. if (!source) {
  33666. return this._sourceNormals;
  33667. }
  33668. this._sourceNormals = new Float32Array(source);
  33669. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33670. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33671. }
  33672. }
  33673. return this._sourceNormals;
  33674. };
  33675. /**
  33676. * Updates the vertex buffer by applying transformation from the bones.
  33677. * Returns the Mesh.
  33678. *
  33679. * @param {skeleton} skeleton to apply
  33680. */
  33681. Mesh.prototype.applySkeleton = function (skeleton) {
  33682. if (!this.geometry) {
  33683. return this;
  33684. }
  33685. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33686. return this;
  33687. }
  33688. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33689. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33690. return this;
  33691. }
  33692. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33693. return this;
  33694. }
  33695. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33696. return this;
  33697. }
  33698. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33699. return this;
  33700. }
  33701. if (!this._sourcePositions) {
  33702. var submeshes = this.subMeshes.slice();
  33703. this.setPositionsForCPUSkinning();
  33704. this.subMeshes = submeshes;
  33705. }
  33706. if (!this._sourceNormals) {
  33707. this.setNormalsForCPUSkinning();
  33708. }
  33709. // positionsData checks for not being Float32Array will only pass at most once
  33710. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33711. if (!positionsData) {
  33712. return this;
  33713. }
  33714. if (!(positionsData instanceof Float32Array)) {
  33715. positionsData = new Float32Array(positionsData);
  33716. }
  33717. // normalsData checks for not being Float32Array will only pass at most once
  33718. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33719. if (!normalsData) {
  33720. return this;
  33721. }
  33722. if (!(normalsData instanceof Float32Array)) {
  33723. normalsData = new Float32Array(normalsData);
  33724. }
  33725. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33726. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33727. if (!matricesWeightsData || !matricesIndicesData) {
  33728. return this;
  33729. }
  33730. var needExtras = this.numBoneInfluencers > 4;
  33731. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33732. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33733. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33734. var tempVector3 = BABYLON.Vector3.Zero();
  33735. var finalMatrix = new BABYLON.Matrix();
  33736. var tempMatrix = new BABYLON.Matrix();
  33737. var matWeightIdx = 0;
  33738. var inf;
  33739. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33740. var weight;
  33741. for (inf = 0; inf < 4; inf++) {
  33742. weight = matricesWeightsData[matWeightIdx + inf];
  33743. if (weight > 0) {
  33744. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33745. finalMatrix.addToSelf(tempMatrix);
  33746. }
  33747. }
  33748. if (needExtras) {
  33749. for (inf = 0; inf < 4; inf++) {
  33750. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33751. if (weight > 0) {
  33752. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33753. finalMatrix.addToSelf(tempMatrix);
  33754. }
  33755. }
  33756. }
  33757. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33758. tempVector3.toArray(positionsData, index);
  33759. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33760. tempVector3.toArray(normalsData, index);
  33761. finalMatrix.reset();
  33762. }
  33763. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33764. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33765. return this;
  33766. };
  33767. // Tools
  33768. /**
  33769. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33770. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33771. */
  33772. Mesh.MinMax = function (meshes) {
  33773. var minVector = null;
  33774. var maxVector = null;
  33775. meshes.forEach(function (mesh, index, array) {
  33776. var boundingInfo = mesh.getBoundingInfo();
  33777. var boundingBox = boundingInfo.boundingBox;
  33778. if (!minVector || !maxVector) {
  33779. minVector = boundingBox.minimumWorld;
  33780. maxVector = boundingBox.maximumWorld;
  33781. }
  33782. else {
  33783. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33784. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33785. }
  33786. });
  33787. if (!minVector || !maxVector) {
  33788. return {
  33789. min: BABYLON.Vector3.Zero(),
  33790. max: BABYLON.Vector3.Zero()
  33791. };
  33792. }
  33793. return {
  33794. min: minVector,
  33795. max: maxVector
  33796. };
  33797. };
  33798. /**
  33799. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33800. */
  33801. Mesh.Center = function (meshesOrMinMaxVector) {
  33802. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33803. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33804. };
  33805. /**
  33806. * Merge the array of meshes into a single mesh for performance reasons.
  33807. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33808. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33809. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33810. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33811. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33812. */
  33813. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33814. if (disposeSource === void 0) { disposeSource = true; }
  33815. var index;
  33816. if (!allow32BitsIndices) {
  33817. var totalVertices = 0;
  33818. // Counting vertices
  33819. for (index = 0; index < meshes.length; index++) {
  33820. if (meshes[index]) {
  33821. totalVertices += meshes[index].getTotalVertices();
  33822. if (totalVertices > 65536) {
  33823. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33824. return null;
  33825. }
  33826. }
  33827. }
  33828. }
  33829. // Merge
  33830. var vertexData = null;
  33831. var otherVertexData;
  33832. var indiceArray = new Array();
  33833. var source = null;
  33834. for (index = 0; index < meshes.length; index++) {
  33835. if (meshes[index]) {
  33836. meshes[index].computeWorldMatrix(true);
  33837. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33838. otherVertexData.transform(meshes[index].getWorldMatrix());
  33839. if (vertexData) {
  33840. vertexData.merge(otherVertexData);
  33841. }
  33842. else {
  33843. vertexData = otherVertexData;
  33844. source = meshes[index];
  33845. }
  33846. if (subdivideWithSubMeshes) {
  33847. indiceArray.push(meshes[index].getTotalIndices());
  33848. }
  33849. }
  33850. }
  33851. source = source;
  33852. if (!meshSubclass) {
  33853. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33854. }
  33855. vertexData.applyToMesh(meshSubclass);
  33856. // Setting properties
  33857. meshSubclass.material = source.material;
  33858. meshSubclass.checkCollisions = source.checkCollisions;
  33859. // Cleaning
  33860. if (disposeSource) {
  33861. for (index = 0; index < meshes.length; index++) {
  33862. if (meshes[index]) {
  33863. meshes[index].dispose();
  33864. }
  33865. }
  33866. }
  33867. // Subdivide
  33868. if (subdivideWithSubMeshes) {
  33869. //-- removal of global submesh
  33870. meshSubclass.releaseSubMeshes();
  33871. index = 0;
  33872. var offset = 0;
  33873. //-- apply subdivision according to index table
  33874. while (index < indiceArray.length) {
  33875. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33876. offset += indiceArray[index];
  33877. index++;
  33878. }
  33879. }
  33880. return meshSubclass;
  33881. };
  33882. // Consts
  33883. Mesh._FRONTSIDE = 0;
  33884. Mesh._BACKSIDE = 1;
  33885. Mesh._DOUBLESIDE = 2;
  33886. Mesh._DEFAULTSIDE = 0;
  33887. Mesh._NO_CAP = 0;
  33888. Mesh._CAP_START = 1;
  33889. Mesh._CAP_END = 2;
  33890. Mesh._CAP_ALL = 3;
  33891. return Mesh;
  33892. }(BABYLON.AbstractMesh));
  33893. BABYLON.Mesh = Mesh;
  33894. })(BABYLON || (BABYLON = {}));
  33895. //# sourceMappingURL=babylon.mesh.js.map
  33896. var BABYLON;
  33897. (function (BABYLON) {
  33898. var BaseSubMesh = /** @class */ (function () {
  33899. function BaseSubMesh() {
  33900. }
  33901. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33902. get: function () {
  33903. return this._materialEffect;
  33904. },
  33905. enumerable: true,
  33906. configurable: true
  33907. });
  33908. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33909. if (defines === void 0) { defines = null; }
  33910. if (this._materialEffect === effect) {
  33911. if (!effect) {
  33912. this._materialDefines = null;
  33913. }
  33914. return;
  33915. }
  33916. this._materialDefines = defines;
  33917. this._materialEffect = effect;
  33918. };
  33919. return BaseSubMesh;
  33920. }());
  33921. BABYLON.BaseSubMesh = BaseSubMesh;
  33922. var SubMesh = /** @class */ (function (_super) {
  33923. __extends(SubMesh, _super);
  33924. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33925. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33926. var _this = _super.call(this) || this;
  33927. _this.materialIndex = materialIndex;
  33928. _this.verticesStart = verticesStart;
  33929. _this.verticesCount = verticesCount;
  33930. _this.indexStart = indexStart;
  33931. _this.indexCount = indexCount;
  33932. _this._renderId = 0;
  33933. _this._mesh = mesh;
  33934. _this._renderingMesh = renderingMesh || mesh;
  33935. mesh.subMeshes.push(_this);
  33936. _this._trianglePlanes = [];
  33937. _this._id = mesh.subMeshes.length - 1;
  33938. if (createBoundingBox) {
  33939. _this.refreshBoundingInfo();
  33940. mesh.computeWorldMatrix(true);
  33941. }
  33942. return _this;
  33943. }
  33944. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33945. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33946. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33947. };
  33948. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33949. get: function () {
  33950. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33951. },
  33952. enumerable: true,
  33953. configurable: true
  33954. });
  33955. /**
  33956. * Returns the submesh BoudingInfo object.
  33957. */
  33958. SubMesh.prototype.getBoundingInfo = function () {
  33959. if (this.IsGlobal) {
  33960. return this._mesh.getBoundingInfo();
  33961. }
  33962. return this._boundingInfo;
  33963. };
  33964. /**
  33965. * Sets the submesh BoundingInfo.
  33966. * Return the SubMesh.
  33967. */
  33968. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33969. this._boundingInfo = boundingInfo;
  33970. return this;
  33971. };
  33972. /**
  33973. * Returns the mesh of the current submesh.
  33974. */
  33975. SubMesh.prototype.getMesh = function () {
  33976. return this._mesh;
  33977. };
  33978. /**
  33979. * Returns the rendering mesh of the submesh.
  33980. */
  33981. SubMesh.prototype.getRenderingMesh = function () {
  33982. return this._renderingMesh;
  33983. };
  33984. /**
  33985. * Returns the submesh material.
  33986. */
  33987. SubMesh.prototype.getMaterial = function () {
  33988. var rootMaterial = this._renderingMesh.material;
  33989. if (rootMaterial === null || rootMaterial === undefined) {
  33990. return this._mesh.getScene().defaultMaterial;
  33991. }
  33992. else if (rootMaterial.getSubMaterial) {
  33993. var multiMaterial = rootMaterial;
  33994. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33995. if (this._currentMaterial !== effectiveMaterial) {
  33996. this._currentMaterial = effectiveMaterial;
  33997. this._materialDefines = null;
  33998. }
  33999. return effectiveMaterial;
  34000. }
  34001. return rootMaterial;
  34002. };
  34003. // Methods
  34004. /**
  34005. * Sets a new updated BoundingInfo object to the submesh.
  34006. * Returns the SubMesh.
  34007. */
  34008. SubMesh.prototype.refreshBoundingInfo = function () {
  34009. this._lastColliderWorldVertices = null;
  34010. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34011. return this;
  34012. }
  34013. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34014. if (!data) {
  34015. this._boundingInfo = this._mesh.getBoundingInfo();
  34016. return this;
  34017. }
  34018. var indices = this._renderingMesh.getIndices();
  34019. var extend;
  34020. //is this the only submesh?
  34021. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34022. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34023. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34024. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34025. }
  34026. else {
  34027. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34028. }
  34029. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34030. return this;
  34031. };
  34032. SubMesh.prototype._checkCollision = function (collider) {
  34033. var boundingInfo = this.getBoundingInfo();
  34034. return boundingInfo._checkCollision(collider);
  34035. };
  34036. /**
  34037. * Updates the submesh BoundingInfo.
  34038. * Returns the Submesh.
  34039. */
  34040. SubMesh.prototype.updateBoundingInfo = function (world) {
  34041. var boundingInfo = this.getBoundingInfo();
  34042. if (!boundingInfo) {
  34043. this.refreshBoundingInfo();
  34044. boundingInfo = this.getBoundingInfo();
  34045. }
  34046. boundingInfo.update(world);
  34047. return this;
  34048. };
  34049. /**
  34050. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34051. * Boolean returned.
  34052. */
  34053. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34054. var boundingInfo = this.getBoundingInfo();
  34055. if (!boundingInfo) {
  34056. return false;
  34057. }
  34058. return boundingInfo.isInFrustum(frustumPlanes);
  34059. };
  34060. /**
  34061. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34062. * Boolean returned.
  34063. */
  34064. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34065. var boundingInfo = this.getBoundingInfo();
  34066. if (!boundingInfo) {
  34067. return false;
  34068. }
  34069. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34070. };
  34071. /**
  34072. * Renders the submesh.
  34073. * Returns it.
  34074. */
  34075. SubMesh.prototype.render = function (enableAlphaMode) {
  34076. this._renderingMesh.render(this, enableAlphaMode);
  34077. return this;
  34078. };
  34079. /**
  34080. * Returns a new Index Buffer.
  34081. * Type returned : WebGLBuffer.
  34082. */
  34083. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34084. if (!this._linesIndexBuffer) {
  34085. var linesIndices = [];
  34086. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34087. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34088. }
  34089. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34090. this.linesIndexCount = linesIndices.length;
  34091. }
  34092. return this._linesIndexBuffer;
  34093. };
  34094. /**
  34095. * True is the passed Ray intersects the submesh bounding box.
  34096. * Boolean returned.
  34097. */
  34098. SubMesh.prototype.canIntersects = function (ray) {
  34099. var boundingInfo = this.getBoundingInfo();
  34100. if (!boundingInfo) {
  34101. return false;
  34102. }
  34103. return ray.intersectsBox(boundingInfo.boundingBox);
  34104. };
  34105. /**
  34106. * Returns an object IntersectionInfo.
  34107. */
  34108. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34109. var intersectInfo = null;
  34110. var material = this.getMaterial();
  34111. if (!material) {
  34112. return null;
  34113. }
  34114. switch (material.fillMode) {
  34115. case BABYLON.Material.PointListDrawMode:
  34116. case BABYLON.Material.LineListDrawMode:
  34117. case BABYLON.Material.LineLoopDrawMode:
  34118. case BABYLON.Material.LineStripDrawMode:
  34119. case BABYLON.Material.TriangleFanDrawMode:
  34120. case BABYLON.Material.TriangleStripDrawMode:
  34121. return null;
  34122. }
  34123. // LineMesh first as it's also a Mesh...
  34124. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34125. var lineMesh = this._mesh;
  34126. // Line test
  34127. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34128. var p0 = positions[indices[index]];
  34129. var p1 = positions[indices[index + 1]];
  34130. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34131. if (length < 0) {
  34132. continue;
  34133. }
  34134. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34135. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34136. if (fastCheck) {
  34137. break;
  34138. }
  34139. }
  34140. }
  34141. }
  34142. else {
  34143. // Triangles test
  34144. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34145. var p0 = positions[indices[index]];
  34146. var p1 = positions[indices[index + 1]];
  34147. var p2 = positions[indices[index + 2]];
  34148. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34149. if (currentIntersectInfo) {
  34150. if (currentIntersectInfo.distance < 0) {
  34151. continue;
  34152. }
  34153. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34154. intersectInfo = currentIntersectInfo;
  34155. intersectInfo.faceId = index / 3;
  34156. if (fastCheck) {
  34157. break;
  34158. }
  34159. }
  34160. }
  34161. }
  34162. }
  34163. return intersectInfo;
  34164. };
  34165. SubMesh.prototype._rebuild = function () {
  34166. if (this._linesIndexBuffer) {
  34167. this._linesIndexBuffer = null;
  34168. }
  34169. };
  34170. // Clone
  34171. /**
  34172. * Creates a new Submesh from the passed Mesh.
  34173. */
  34174. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34175. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34176. if (!this.IsGlobal) {
  34177. var boundingInfo = this.getBoundingInfo();
  34178. if (!boundingInfo) {
  34179. return result;
  34180. }
  34181. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34182. }
  34183. return result;
  34184. };
  34185. // Dispose
  34186. /**
  34187. * Disposes the Submesh.
  34188. * Returns nothing.
  34189. */
  34190. SubMesh.prototype.dispose = function () {
  34191. if (this._linesIndexBuffer) {
  34192. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34193. this._linesIndexBuffer = null;
  34194. }
  34195. // Remove from mesh
  34196. var index = this._mesh.subMeshes.indexOf(this);
  34197. this._mesh.subMeshes.splice(index, 1);
  34198. };
  34199. // Statics
  34200. /**
  34201. * Creates a new Submesh from the passed parameters :
  34202. * - materialIndex (integer) : the index of the main mesh material.
  34203. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34204. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34205. * - mesh (Mesh) : the main mesh to create the submesh from.
  34206. * - renderingMesh (optional Mesh) : rendering mesh.
  34207. */
  34208. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34209. var minVertexIndex = Number.MAX_VALUE;
  34210. var maxVertexIndex = -Number.MAX_VALUE;
  34211. renderingMesh = (renderingMesh || mesh);
  34212. var indices = renderingMesh.getIndices();
  34213. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34214. var vertexIndex = indices[index];
  34215. if (vertexIndex < minVertexIndex)
  34216. minVertexIndex = vertexIndex;
  34217. if (vertexIndex > maxVertexIndex)
  34218. maxVertexIndex = vertexIndex;
  34219. }
  34220. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34221. };
  34222. return SubMesh;
  34223. }(BaseSubMesh));
  34224. BABYLON.SubMesh = SubMesh;
  34225. })(BABYLON || (BABYLON = {}));
  34226. //# sourceMappingURL=babylon.subMesh.js.map
  34227. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34228. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34229. s = arguments[i];
  34230. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34231. t[p] = s[p];
  34232. }
  34233. return t;
  34234. };
  34235. var BABYLON;
  34236. (function (BABYLON) {
  34237. /**
  34238. * Manages the defines for the Material
  34239. */
  34240. var MaterialDefines = /** @class */ (function () {
  34241. function MaterialDefines() {
  34242. this._isDirty = true;
  34243. /** @hidden */
  34244. this._areLightsDirty = true;
  34245. /** @hidden */
  34246. this._areAttributesDirty = true;
  34247. /** @hidden */
  34248. this._areTexturesDirty = true;
  34249. /** @hidden */
  34250. this._areFresnelDirty = true;
  34251. /** @hidden */
  34252. this._areMiscDirty = true;
  34253. /** @hidden */
  34254. this._areImageProcessingDirty = true;
  34255. /** @hidden */
  34256. this._normals = false;
  34257. /** @hidden */
  34258. this._uvs = false;
  34259. /** @hidden */
  34260. this._needNormals = false;
  34261. /** @hidden */
  34262. this._needUVs = false;
  34263. }
  34264. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34265. /**
  34266. * Specifies if the material needs to be re-calculated
  34267. */
  34268. get: function () {
  34269. return this._isDirty;
  34270. },
  34271. enumerable: true,
  34272. configurable: true
  34273. });
  34274. /**
  34275. * Marks the material to indicate that it has been re-calculated
  34276. */
  34277. MaterialDefines.prototype.markAsProcessed = function () {
  34278. this._isDirty = false;
  34279. this._areAttributesDirty = false;
  34280. this._areTexturesDirty = false;
  34281. this._areFresnelDirty = false;
  34282. this._areLightsDirty = false;
  34283. this._areMiscDirty = false;
  34284. this._areImageProcessingDirty = false;
  34285. };
  34286. /**
  34287. * Marks the material to indicate that it needs to be re-calculated
  34288. */
  34289. MaterialDefines.prototype.markAsUnprocessed = function () {
  34290. this._isDirty = true;
  34291. };
  34292. /**
  34293. * Marks the material to indicate all of its defines need to be re-calculated
  34294. */
  34295. MaterialDefines.prototype.markAllAsDirty = function () {
  34296. this._areTexturesDirty = true;
  34297. this._areAttributesDirty = true;
  34298. this._areLightsDirty = true;
  34299. this._areFresnelDirty = true;
  34300. this._areMiscDirty = true;
  34301. this._areImageProcessingDirty = true;
  34302. this._isDirty = true;
  34303. };
  34304. /**
  34305. * Marks the material to indicate that image processing needs to be re-calculated
  34306. */
  34307. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34308. this._areImageProcessingDirty = true;
  34309. this._isDirty = true;
  34310. };
  34311. /**
  34312. * Marks the material to indicate the lights need to be re-calculated
  34313. */
  34314. MaterialDefines.prototype.markAsLightDirty = function () {
  34315. this._areLightsDirty = true;
  34316. this._isDirty = true;
  34317. };
  34318. /**
  34319. * Marks the attribute state as changed
  34320. */
  34321. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34322. this._areAttributesDirty = true;
  34323. this._isDirty = true;
  34324. };
  34325. /**
  34326. * Marks the texture state as changed
  34327. */
  34328. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34329. this._areTexturesDirty = true;
  34330. this._isDirty = true;
  34331. };
  34332. /**
  34333. * Marks the fresnel state as changed
  34334. */
  34335. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34336. this._areFresnelDirty = true;
  34337. this._isDirty = true;
  34338. };
  34339. /**
  34340. * Marks the misc state as changed
  34341. */
  34342. MaterialDefines.prototype.markAsMiscDirty = function () {
  34343. this._areMiscDirty = true;
  34344. this._isDirty = true;
  34345. };
  34346. /**
  34347. * Rebuilds the material defines
  34348. */
  34349. MaterialDefines.prototype.rebuild = function () {
  34350. if (this._keys) {
  34351. delete this._keys;
  34352. }
  34353. this._keys = [];
  34354. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34355. var key = _a[_i];
  34356. if (key[0] === "_") {
  34357. continue;
  34358. }
  34359. this._keys.push(key);
  34360. }
  34361. };
  34362. /**
  34363. * Specifies if two material defines are equal
  34364. * @param other - A material define instance to compare to
  34365. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34366. */
  34367. MaterialDefines.prototype.isEqual = function (other) {
  34368. if (this._keys.length !== other._keys.length) {
  34369. return false;
  34370. }
  34371. for (var index = 0; index < this._keys.length; index++) {
  34372. var prop = this._keys[index];
  34373. if (this[prop] !== other[prop]) {
  34374. return false;
  34375. }
  34376. }
  34377. return true;
  34378. };
  34379. /**
  34380. * Clones this instance's defines to another instance
  34381. * @param other - material defines to clone values to
  34382. */
  34383. MaterialDefines.prototype.cloneTo = function (other) {
  34384. if (this._keys.length !== other._keys.length) {
  34385. other._keys = this._keys.slice(0);
  34386. }
  34387. for (var index = 0; index < this._keys.length; index++) {
  34388. var prop = this._keys[index];
  34389. other[prop] = this[prop];
  34390. }
  34391. };
  34392. /**
  34393. * Resets the material define values
  34394. */
  34395. MaterialDefines.prototype.reset = function () {
  34396. for (var index = 0; index < this._keys.length; index++) {
  34397. var prop = this._keys[index];
  34398. var type = typeof this[prop];
  34399. switch (type) {
  34400. case "number":
  34401. this[prop] = 0;
  34402. break;
  34403. case "string":
  34404. this[prop] = "";
  34405. break;
  34406. default:
  34407. this[prop] = false;
  34408. break;
  34409. }
  34410. }
  34411. };
  34412. /**
  34413. * Converts the material define values to a string
  34414. * @returns - String of material define information
  34415. */
  34416. MaterialDefines.prototype.toString = function () {
  34417. var result = "";
  34418. for (var index = 0; index < this._keys.length; index++) {
  34419. var prop = this._keys[index];
  34420. var value = this[prop];
  34421. var type = typeof value;
  34422. switch (type) {
  34423. case "number":
  34424. case "string":
  34425. result += "#define " + prop + " " + value + "\n";
  34426. break;
  34427. default:
  34428. if (value) {
  34429. result += "#define " + prop + "\n";
  34430. }
  34431. break;
  34432. }
  34433. }
  34434. return result;
  34435. };
  34436. return MaterialDefines;
  34437. }());
  34438. BABYLON.MaterialDefines = MaterialDefines;
  34439. /**
  34440. * Base class for the main features of a material in Babylon.js
  34441. */
  34442. var Material = /** @class */ (function () {
  34443. /**
  34444. * Creates a material instance
  34445. * @param name defines the name of the material
  34446. * @param scene defines the scene to reference
  34447. * @param doNotAdd specifies if the material should be added to the scene
  34448. */
  34449. function Material(name, scene, doNotAdd) {
  34450. /**
  34451. * Specifies if the ready state should be checked on each call
  34452. */
  34453. this.checkReadyOnEveryCall = false;
  34454. /**
  34455. * Specifies if the ready state should be checked once
  34456. */
  34457. this.checkReadyOnlyOnce = false;
  34458. /**
  34459. * The state of the material
  34460. */
  34461. this.state = "";
  34462. /**
  34463. * The alpha value of the material
  34464. */
  34465. this._alpha = 1.0;
  34466. /**
  34467. * Specifies if back face culling is enabled
  34468. */
  34469. this._backFaceCulling = true;
  34470. /**
  34471. * Specifies if the material should be serialized
  34472. */
  34473. this.doNotSerialize = false;
  34474. /**
  34475. * Specifies if the effect should be stored on sub meshes
  34476. */
  34477. this.storeEffectOnSubMeshes = false;
  34478. /**
  34479. * An event triggered when the material is disposed
  34480. */
  34481. this.onDisposeObservable = new BABYLON.Observable();
  34482. /**
  34483. * An event triggered when the material is bound
  34484. */
  34485. this.onBindObservable = new BABYLON.Observable();
  34486. /**
  34487. * An event triggered when the material is unbound
  34488. */
  34489. this.onUnBindObservable = new BABYLON.Observable();
  34490. /**
  34491. * Stores the value of the alpha mode
  34492. */
  34493. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34494. /**
  34495. * Stores the state of the need depth pre-pass value
  34496. */
  34497. this._needDepthPrePass = false;
  34498. /**
  34499. * Specifies if depth writing should be disabled
  34500. */
  34501. this.disableDepthWrite = false;
  34502. /**
  34503. * Specifies if depth writing should be forced
  34504. */
  34505. this.forceDepthWrite = false;
  34506. /**
  34507. * Specifies if there should be a separate pass for culling
  34508. */
  34509. this.separateCullingPass = false;
  34510. /**
  34511. * Stores the state specifing if fog should be enabled
  34512. */
  34513. this._fogEnabled = true;
  34514. /**
  34515. * Stores the size of points
  34516. */
  34517. this.pointSize = 1.0;
  34518. /**
  34519. * Stores the z offset value
  34520. */
  34521. this.zOffset = 0;
  34522. /**
  34523. * Specifies if the material was previously ready
  34524. */
  34525. this._wasPreviouslyReady = false;
  34526. /**
  34527. * Stores the fill mode state
  34528. */
  34529. this._fillMode = Material.TriangleFillMode;
  34530. this.name = name;
  34531. this.id = name || BABYLON.Tools.RandomId();
  34532. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34533. this.uniqueId = this._scene.getUniqueId();
  34534. if (this._scene.useRightHandedSystem) {
  34535. this.sideOrientation = Material.ClockWiseSideOrientation;
  34536. }
  34537. else {
  34538. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34539. }
  34540. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34541. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34542. if (!doNotAdd) {
  34543. this._scene.materials.push(this);
  34544. }
  34545. }
  34546. Object.defineProperty(Material, "TriangleFillMode", {
  34547. /**
  34548. * Returns the triangle fill mode
  34549. */
  34550. get: function () {
  34551. return Material._TriangleFillMode;
  34552. },
  34553. enumerable: true,
  34554. configurable: true
  34555. });
  34556. Object.defineProperty(Material, "WireFrameFillMode", {
  34557. /**
  34558. * Returns the wireframe mode
  34559. */
  34560. get: function () {
  34561. return Material._WireFrameFillMode;
  34562. },
  34563. enumerable: true,
  34564. configurable: true
  34565. });
  34566. Object.defineProperty(Material, "PointFillMode", {
  34567. /**
  34568. * Returns the point fill mode
  34569. */
  34570. get: function () {
  34571. return Material._PointFillMode;
  34572. },
  34573. enumerable: true,
  34574. configurable: true
  34575. });
  34576. Object.defineProperty(Material, "PointListDrawMode", {
  34577. /**
  34578. * Returns the point list draw mode
  34579. */
  34580. get: function () {
  34581. return Material._PointListDrawMode;
  34582. },
  34583. enumerable: true,
  34584. configurable: true
  34585. });
  34586. Object.defineProperty(Material, "LineListDrawMode", {
  34587. /**
  34588. * Returns the line list draw mode
  34589. */
  34590. get: function () {
  34591. return Material._LineListDrawMode;
  34592. },
  34593. enumerable: true,
  34594. configurable: true
  34595. });
  34596. Object.defineProperty(Material, "LineLoopDrawMode", {
  34597. /**
  34598. * Returns the line loop draw mode
  34599. */
  34600. get: function () {
  34601. return Material._LineLoopDrawMode;
  34602. },
  34603. enumerable: true,
  34604. configurable: true
  34605. });
  34606. Object.defineProperty(Material, "LineStripDrawMode", {
  34607. /**
  34608. * Returns the line strip draw mode
  34609. */
  34610. get: function () {
  34611. return Material._LineStripDrawMode;
  34612. },
  34613. enumerable: true,
  34614. configurable: true
  34615. });
  34616. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34617. /**
  34618. * Returns the triangle strip draw mode
  34619. */
  34620. get: function () {
  34621. return Material._TriangleStripDrawMode;
  34622. },
  34623. enumerable: true,
  34624. configurable: true
  34625. });
  34626. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34627. /**
  34628. * Returns the triangle fan draw mode
  34629. */
  34630. get: function () {
  34631. return Material._TriangleFanDrawMode;
  34632. },
  34633. enumerable: true,
  34634. configurable: true
  34635. });
  34636. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34637. /**
  34638. * Returns the clock-wise side orientation
  34639. */
  34640. get: function () {
  34641. return Material._ClockWiseSideOrientation;
  34642. },
  34643. enumerable: true,
  34644. configurable: true
  34645. });
  34646. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34647. /**
  34648. * Returns the counter clock-wise side orientation
  34649. */
  34650. get: function () {
  34651. return Material._CounterClockWiseSideOrientation;
  34652. },
  34653. enumerable: true,
  34654. configurable: true
  34655. });
  34656. Object.defineProperty(Material, "TextureDirtyFlag", {
  34657. /**
  34658. * Returns the dirty texture flag value
  34659. */
  34660. get: function () {
  34661. return Material._TextureDirtyFlag;
  34662. },
  34663. enumerable: true,
  34664. configurable: true
  34665. });
  34666. Object.defineProperty(Material, "LightDirtyFlag", {
  34667. /**
  34668. * Returns the dirty light flag value
  34669. */
  34670. get: function () {
  34671. return Material._LightDirtyFlag;
  34672. },
  34673. enumerable: true,
  34674. configurable: true
  34675. });
  34676. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34677. /**
  34678. * Returns the dirty fresnel flag value
  34679. */
  34680. get: function () {
  34681. return Material._FresnelDirtyFlag;
  34682. },
  34683. enumerable: true,
  34684. configurable: true
  34685. });
  34686. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34687. /**
  34688. * Returns the dirty attributes flag value
  34689. */
  34690. get: function () {
  34691. return Material._AttributesDirtyFlag;
  34692. },
  34693. enumerable: true,
  34694. configurable: true
  34695. });
  34696. Object.defineProperty(Material, "MiscDirtyFlag", {
  34697. /**
  34698. * Returns the dirty misc flag value
  34699. */
  34700. get: function () {
  34701. return Material._MiscDirtyFlag;
  34702. },
  34703. enumerable: true,
  34704. configurable: true
  34705. });
  34706. Object.defineProperty(Material.prototype, "alpha", {
  34707. /**
  34708. * Gets the alpha value of the material
  34709. */
  34710. get: function () {
  34711. return this._alpha;
  34712. },
  34713. /**
  34714. * Sets the alpha value of the material
  34715. */
  34716. set: function (value) {
  34717. if (this._alpha === value) {
  34718. return;
  34719. }
  34720. this._alpha = value;
  34721. this.markAsDirty(Material.MiscDirtyFlag);
  34722. },
  34723. enumerable: true,
  34724. configurable: true
  34725. });
  34726. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34727. /**
  34728. * Gets the back-face culling state
  34729. */
  34730. get: function () {
  34731. return this._backFaceCulling;
  34732. },
  34733. /**
  34734. * Sets the back-face culling state
  34735. */
  34736. set: function (value) {
  34737. if (this._backFaceCulling === value) {
  34738. return;
  34739. }
  34740. this._backFaceCulling = value;
  34741. this.markAsDirty(Material.TextureDirtyFlag);
  34742. },
  34743. enumerable: true,
  34744. configurable: true
  34745. });
  34746. Object.defineProperty(Material.prototype, "onDispose", {
  34747. /**
  34748. * Called during a dispose event
  34749. */
  34750. set: function (callback) {
  34751. if (this._onDisposeObserver) {
  34752. this.onDisposeObservable.remove(this._onDisposeObserver);
  34753. }
  34754. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34755. },
  34756. enumerable: true,
  34757. configurable: true
  34758. });
  34759. Object.defineProperty(Material.prototype, "onBind", {
  34760. /**
  34761. * Called during a bind event
  34762. */
  34763. set: function (callback) {
  34764. if (this._onBindObserver) {
  34765. this.onBindObservable.remove(this._onBindObserver);
  34766. }
  34767. this._onBindObserver = this.onBindObservable.add(callback);
  34768. },
  34769. enumerable: true,
  34770. configurable: true
  34771. });
  34772. Object.defineProperty(Material.prototype, "alphaMode", {
  34773. /**
  34774. * Gets the value of the alpha mode
  34775. */
  34776. get: function () {
  34777. return this._alphaMode;
  34778. },
  34779. /**
  34780. * Sets the value of the alpha mode.
  34781. *
  34782. * | Value | Type | Description |
  34783. * | --- | --- | --- |
  34784. * | 0 | ALPHA_DISABLE | |
  34785. * | 1 | ALPHA_ADD | |
  34786. * | 2 | ALPHA_COMBINE | |
  34787. * | 3 | ALPHA_SUBTRACT | |
  34788. * | 4 | ALPHA_MULTIPLY | |
  34789. * | 5 | ALPHA_MAXIMIZED | |
  34790. * | 6 | ALPHA_ONEONE | |
  34791. * | 7 | ALPHA_PREMULTIPLIED | |
  34792. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34793. * | 9 | ALPHA_INTERPOLATE | |
  34794. * | 10 | ALPHA_SCREENMODE | |
  34795. *
  34796. */
  34797. set: function (value) {
  34798. if (this._alphaMode === value) {
  34799. return;
  34800. }
  34801. this._alphaMode = value;
  34802. this.markAsDirty(Material.TextureDirtyFlag);
  34803. },
  34804. enumerable: true,
  34805. configurable: true
  34806. });
  34807. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34808. /**
  34809. * Gets the depth pre-pass value
  34810. */
  34811. get: function () {
  34812. return this._needDepthPrePass;
  34813. },
  34814. /**
  34815. * Sets the need depth pre-pass value
  34816. */
  34817. set: function (value) {
  34818. if (this._needDepthPrePass === value) {
  34819. return;
  34820. }
  34821. this._needDepthPrePass = value;
  34822. if (this._needDepthPrePass) {
  34823. this.checkReadyOnEveryCall = true;
  34824. }
  34825. },
  34826. enumerable: true,
  34827. configurable: true
  34828. });
  34829. Object.defineProperty(Material.prototype, "fogEnabled", {
  34830. /**
  34831. * Gets the value of the fog enabled state
  34832. */
  34833. get: function () {
  34834. return this._fogEnabled;
  34835. },
  34836. /**
  34837. * Sets the state for enabling fog
  34838. */
  34839. set: function (value) {
  34840. if (this._fogEnabled === value) {
  34841. return;
  34842. }
  34843. this._fogEnabled = value;
  34844. this.markAsDirty(Material.MiscDirtyFlag);
  34845. },
  34846. enumerable: true,
  34847. configurable: true
  34848. });
  34849. Object.defineProperty(Material.prototype, "wireframe", {
  34850. /**
  34851. * Gets a value specifying if wireframe mode is enabled
  34852. */
  34853. get: function () {
  34854. switch (this._fillMode) {
  34855. case Material.WireFrameFillMode:
  34856. case Material.LineListDrawMode:
  34857. case Material.LineLoopDrawMode:
  34858. case Material.LineStripDrawMode:
  34859. return true;
  34860. }
  34861. return this._scene.forceWireframe;
  34862. },
  34863. /**
  34864. * Sets the state of wireframe mode
  34865. */
  34866. set: function (value) {
  34867. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(Material.prototype, "pointsCloud", {
  34873. /**
  34874. * Gets the value specifying if point clouds are enabled
  34875. */
  34876. get: function () {
  34877. switch (this._fillMode) {
  34878. case Material.PointFillMode:
  34879. case Material.PointListDrawMode:
  34880. return true;
  34881. }
  34882. return this._scene.forcePointsCloud;
  34883. },
  34884. /**
  34885. * Sets the state of point cloud mode
  34886. */
  34887. set: function (value) {
  34888. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34889. },
  34890. enumerable: true,
  34891. configurable: true
  34892. });
  34893. Object.defineProperty(Material.prototype, "fillMode", {
  34894. /**
  34895. * Gets the material fill mode
  34896. */
  34897. get: function () {
  34898. return this._fillMode;
  34899. },
  34900. /**
  34901. * Sets the material fill mode
  34902. */
  34903. set: function (value) {
  34904. if (this._fillMode === value) {
  34905. return;
  34906. }
  34907. this._fillMode = value;
  34908. this.markAsDirty(Material.MiscDirtyFlag);
  34909. },
  34910. enumerable: true,
  34911. configurable: true
  34912. });
  34913. /**
  34914. * Returns a string representation of the current material
  34915. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34916. * @returns a string with material information
  34917. */
  34918. Material.prototype.toString = function (fullDetails) {
  34919. var ret = "Name: " + this.name;
  34920. if (fullDetails) {
  34921. }
  34922. return ret;
  34923. };
  34924. /**
  34925. * Gets the class name of the material
  34926. * @returns a string with the class name of the material
  34927. */
  34928. Material.prototype.getClassName = function () {
  34929. return "Material";
  34930. };
  34931. Object.defineProperty(Material.prototype, "isFrozen", {
  34932. /**
  34933. * Specifies if updates for the material been locked
  34934. */
  34935. get: function () {
  34936. return this.checkReadyOnlyOnce;
  34937. },
  34938. enumerable: true,
  34939. configurable: true
  34940. });
  34941. /**
  34942. * Locks updates for the material
  34943. */
  34944. Material.prototype.freeze = function () {
  34945. this.checkReadyOnlyOnce = true;
  34946. };
  34947. /**
  34948. * Unlocks updates for the material
  34949. */
  34950. Material.prototype.unfreeze = function () {
  34951. this.checkReadyOnlyOnce = false;
  34952. };
  34953. /**
  34954. * Specifies if the material is ready to be used
  34955. * @param mesh defines the mesh to check
  34956. * @param useInstances specifies if instances should be used
  34957. * @returns a boolean indicating if the material is ready to be used
  34958. */
  34959. Material.prototype.isReady = function (mesh, useInstances) {
  34960. return true;
  34961. };
  34962. /**
  34963. * Specifies that the submesh is ready to be used
  34964. * @param mesh defines the mesh to check
  34965. * @param subMesh defines which submesh to check
  34966. * @param useInstances specifies that instances should be used
  34967. * @returns a boolean indicating that the submesh is ready or not
  34968. */
  34969. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34970. return false;
  34971. };
  34972. /**
  34973. * Returns the material effect
  34974. * @returns the effect associated with the material
  34975. */
  34976. Material.prototype.getEffect = function () {
  34977. return this._effect;
  34978. };
  34979. /**
  34980. * Returns the current scene
  34981. * @returns a Scene
  34982. */
  34983. Material.prototype.getScene = function () {
  34984. return this._scene;
  34985. };
  34986. /**
  34987. * Specifies if the material will require alpha blending
  34988. * @returns a boolean specifying if alpha blending is needed
  34989. */
  34990. Material.prototype.needAlphaBlending = function () {
  34991. return (this.alpha < 1.0);
  34992. };
  34993. /**
  34994. * Specifies if the mesh will require alpha blending
  34995. * @param mesh defines the mesh to check
  34996. * @returns a boolean specifying if alpha blending is needed for the mesh
  34997. */
  34998. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34999. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35000. };
  35001. /**
  35002. * Specifies if this material should be rendered in alpha test mode
  35003. * @returns a boolean specifying if an alpha test is needed.
  35004. */
  35005. Material.prototype.needAlphaTesting = function () {
  35006. return false;
  35007. };
  35008. /**
  35009. * Gets the texture used for the alpha test
  35010. * @returns the texture to use for alpha testing
  35011. */
  35012. Material.prototype.getAlphaTestTexture = function () {
  35013. return null;
  35014. };
  35015. /**
  35016. * Marks the material to indicate that it needs to be re-calculated
  35017. */
  35018. Material.prototype.markDirty = function () {
  35019. this._wasPreviouslyReady = false;
  35020. };
  35021. /** @hidden */
  35022. Material.prototype._preBind = function (effect, overrideOrientation) {
  35023. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35024. var engine = this._scene.getEngine();
  35025. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35026. var reverse = orientation === Material.ClockWiseSideOrientation;
  35027. engine.enableEffect(effect ? effect : this._effect);
  35028. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35029. return reverse;
  35030. };
  35031. /**
  35032. * Binds the material to the mesh
  35033. * @param world defines the world transformation matrix
  35034. * @param mesh defines the mesh to bind the material to
  35035. */
  35036. Material.prototype.bind = function (world, mesh) {
  35037. };
  35038. /**
  35039. * Binds the submesh to the material
  35040. * @param world defines the world transformation matrix
  35041. * @param mesh defines the mesh containing the submesh
  35042. * @param subMesh defines the submesh to bind the material to
  35043. */
  35044. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35045. };
  35046. /**
  35047. * Binds the world matrix to the material
  35048. * @param world defines the world transformation matrix
  35049. */
  35050. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35051. };
  35052. /**
  35053. * Binds the scene's uniform buffer to the effect.
  35054. * @param effect defines the effect to bind to the scene uniform buffer
  35055. * @param sceneUbo defines the uniform buffer storing scene data
  35056. */
  35057. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35058. sceneUbo.bindToEffect(effect, "Scene");
  35059. };
  35060. /**
  35061. * Binds the view matrix to the effect
  35062. * @param effect defines the effect to bind the view matrix to
  35063. */
  35064. Material.prototype.bindView = function (effect) {
  35065. if (!this._useUBO) {
  35066. effect.setMatrix("view", this.getScene().getViewMatrix());
  35067. }
  35068. else {
  35069. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35070. }
  35071. };
  35072. /**
  35073. * Binds the view projection matrix to the effect
  35074. * @param effect defines the effect to bind the view projection matrix to
  35075. */
  35076. Material.prototype.bindViewProjection = function (effect) {
  35077. if (!this._useUBO) {
  35078. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35079. }
  35080. else {
  35081. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35082. }
  35083. };
  35084. /**
  35085. * Specifies if material alpha testing should be turned on for the mesh
  35086. * @param mesh defines the mesh to check
  35087. */
  35088. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35089. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35090. };
  35091. /**
  35092. * Processes to execute after binding the material to a mesh
  35093. * @param mesh defines the rendered mesh
  35094. */
  35095. Material.prototype._afterBind = function (mesh) {
  35096. this._scene._cachedMaterial = this;
  35097. if (mesh) {
  35098. this._scene._cachedVisibility = mesh.visibility;
  35099. }
  35100. else {
  35101. this._scene._cachedVisibility = 1;
  35102. }
  35103. if (mesh) {
  35104. this.onBindObservable.notifyObservers(mesh);
  35105. }
  35106. if (this.disableDepthWrite) {
  35107. var engine = this._scene.getEngine();
  35108. this._cachedDepthWriteState = engine.getDepthWrite();
  35109. engine.setDepthWrite(false);
  35110. }
  35111. };
  35112. /**
  35113. * Unbinds the material from the mesh
  35114. */
  35115. Material.prototype.unbind = function () {
  35116. this.onUnBindObservable.notifyObservers(this);
  35117. if (this.disableDepthWrite) {
  35118. var engine = this._scene.getEngine();
  35119. engine.setDepthWrite(this._cachedDepthWriteState);
  35120. }
  35121. };
  35122. /**
  35123. * Gets the active textures from the material
  35124. * @returns an array of textures
  35125. */
  35126. Material.prototype.getActiveTextures = function () {
  35127. return [];
  35128. };
  35129. /**
  35130. * Specifies if the material uses a texture
  35131. * @param texture defines the texture to check against the material
  35132. * @returns a boolean specifying if the material uses the texture
  35133. */
  35134. Material.prototype.hasTexture = function (texture) {
  35135. return false;
  35136. };
  35137. /**
  35138. * Makes a duplicate of the material, and gives it a new name
  35139. * @param name defines the new name for the duplicated material
  35140. * @returns the cloned material
  35141. */
  35142. Material.prototype.clone = function (name) {
  35143. return null;
  35144. };
  35145. /**
  35146. * Gets the meshes bound to the material
  35147. * @returns an array of meshes bound to the material
  35148. */
  35149. Material.prototype.getBindedMeshes = function () {
  35150. var result = new Array();
  35151. for (var index = 0; index < this._scene.meshes.length; index++) {
  35152. var mesh = this._scene.meshes[index];
  35153. if (mesh.material === this) {
  35154. result.push(mesh);
  35155. }
  35156. }
  35157. return result;
  35158. };
  35159. /**
  35160. * Force shader compilation
  35161. * @param mesh defines the mesh associated with this material
  35162. * @param onCompiled defines a function to execute once the material is compiled
  35163. * @param options defines the options to configure the compilation
  35164. */
  35165. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35166. var _this = this;
  35167. var localOptions = __assign({ clipPlane: false }, options);
  35168. var subMesh = new BABYLON.BaseSubMesh();
  35169. var scene = this.getScene();
  35170. var checkReady = function () {
  35171. if (!_this._scene || !_this._scene.getEngine()) {
  35172. return;
  35173. }
  35174. if (subMesh._materialDefines) {
  35175. subMesh._materialDefines._renderId = -1;
  35176. }
  35177. var clipPlaneState = scene.clipPlane;
  35178. if (localOptions.clipPlane) {
  35179. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35180. }
  35181. if (_this.storeEffectOnSubMeshes) {
  35182. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35183. if (onCompiled) {
  35184. onCompiled(_this);
  35185. }
  35186. }
  35187. else {
  35188. setTimeout(checkReady, 16);
  35189. }
  35190. }
  35191. else {
  35192. if (_this.isReady(mesh)) {
  35193. if (onCompiled) {
  35194. onCompiled(_this);
  35195. }
  35196. }
  35197. else {
  35198. setTimeout(checkReady, 16);
  35199. }
  35200. }
  35201. if (localOptions.clipPlane) {
  35202. scene.clipPlane = clipPlaneState;
  35203. }
  35204. };
  35205. checkReady();
  35206. };
  35207. /**
  35208. * Force shader compilation
  35209. * @param mesh defines the mesh that will use this material
  35210. * @param options defines additional options for compiling the shaders
  35211. * @returns a promise that resolves when the compilation completes
  35212. */
  35213. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35214. var _this = this;
  35215. return new Promise(function (resolve) {
  35216. _this.forceCompilation(mesh, function () {
  35217. resolve();
  35218. }, options);
  35219. });
  35220. };
  35221. /**
  35222. * Marks a define in the material to indicate that it needs to be re-computed
  35223. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35224. */
  35225. Material.prototype.markAsDirty = function (flag) {
  35226. if (flag & Material.TextureDirtyFlag) {
  35227. this._markAllSubMeshesAsTexturesDirty();
  35228. }
  35229. if (flag & Material.LightDirtyFlag) {
  35230. this._markAllSubMeshesAsLightsDirty();
  35231. }
  35232. if (flag & Material.FresnelDirtyFlag) {
  35233. this._markAllSubMeshesAsFresnelDirty();
  35234. }
  35235. if (flag & Material.AttributesDirtyFlag) {
  35236. this._markAllSubMeshesAsAttributesDirty();
  35237. }
  35238. if (flag & Material.MiscDirtyFlag) {
  35239. this._markAllSubMeshesAsMiscDirty();
  35240. }
  35241. this.getScene().resetCachedMaterial();
  35242. };
  35243. /**
  35244. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35245. * @param func defines a function which checks material defines against the submeshes
  35246. */
  35247. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35248. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35249. var mesh = _a[_i];
  35250. if (!mesh.subMeshes) {
  35251. continue;
  35252. }
  35253. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35254. var subMesh = _c[_b];
  35255. if (subMesh.getMaterial() !== this) {
  35256. continue;
  35257. }
  35258. if (!subMesh._materialDefines) {
  35259. continue;
  35260. }
  35261. func(subMesh._materialDefines);
  35262. }
  35263. }
  35264. };
  35265. /**
  35266. * Indicates that image processing needs to be re-calculated for all submeshes
  35267. */
  35268. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35269. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35270. };
  35271. /**
  35272. * Indicates that textures need to be re-calculated for all submeshes
  35273. */
  35274. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35275. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35276. };
  35277. /**
  35278. * Indicates that fresnel needs to be re-calculated for all submeshes
  35279. */
  35280. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35281. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35282. };
  35283. /**
  35284. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35285. */
  35286. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35287. this._markAllSubMeshesAsDirty(function (defines) {
  35288. defines.markAsFresnelDirty();
  35289. defines.markAsMiscDirty();
  35290. });
  35291. };
  35292. /**
  35293. * Indicates that lights need to be re-calculated for all submeshes
  35294. */
  35295. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35296. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35297. };
  35298. /**
  35299. * Indicates that attributes need to be re-calculated for all submeshes
  35300. */
  35301. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35302. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35303. };
  35304. /**
  35305. * Indicates that misc needs to be re-calculated for all submeshes
  35306. */
  35307. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35308. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35309. };
  35310. /**
  35311. * Indicates that textures and misc need to be re-calculated for all submeshes
  35312. */
  35313. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35314. this._markAllSubMeshesAsDirty(function (defines) {
  35315. defines.markAsTexturesDirty();
  35316. defines.markAsMiscDirty();
  35317. });
  35318. };
  35319. /**
  35320. * Disposes the material
  35321. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35322. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35323. */
  35324. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35325. // Animations
  35326. this.getScene().stopAnimation(this);
  35327. this.getScene().freeProcessedMaterials();
  35328. // Remove from scene
  35329. var index = this._scene.materials.indexOf(this);
  35330. if (index >= 0) {
  35331. this._scene.materials.splice(index, 1);
  35332. }
  35333. // Remove from meshes
  35334. for (index = 0; index < this._scene.meshes.length; index++) {
  35335. var mesh = this._scene.meshes[index];
  35336. if (mesh.material === this) {
  35337. mesh.material = null;
  35338. if (mesh.geometry) {
  35339. var geometry = (mesh.geometry);
  35340. if (this.storeEffectOnSubMeshes) {
  35341. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35342. var subMesh = _a[_i];
  35343. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35344. if (forceDisposeEffect && subMesh._materialEffect) {
  35345. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35346. }
  35347. }
  35348. }
  35349. else {
  35350. geometry._releaseVertexArrayObject(this._effect);
  35351. }
  35352. }
  35353. }
  35354. }
  35355. this._uniformBuffer.dispose();
  35356. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35357. if (forceDisposeEffect && this._effect) {
  35358. if (!this.storeEffectOnSubMeshes) {
  35359. this._scene.getEngine()._releaseEffect(this._effect);
  35360. }
  35361. this._effect = null;
  35362. }
  35363. // Callback
  35364. this.onDisposeObservable.notifyObservers(this);
  35365. this.onDisposeObservable.clear();
  35366. this.onBindObservable.clear();
  35367. this.onUnBindObservable.clear();
  35368. };
  35369. /**
  35370. * Serializes this material
  35371. * @returns the serialized material object
  35372. */
  35373. Material.prototype.serialize = function () {
  35374. return BABYLON.SerializationHelper.Serialize(this);
  35375. };
  35376. /**
  35377. * Creates a MultiMaterial from parsed MultiMaterial data.
  35378. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35379. * @param scene defines the hosting scene
  35380. * @returns a new MultiMaterial
  35381. */
  35382. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35383. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35384. multiMaterial.id = parsedMultiMaterial.id;
  35385. if (BABYLON.Tags) {
  35386. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35387. }
  35388. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35389. var subMatId = parsedMultiMaterial.materials[matIndex];
  35390. if (subMatId) {
  35391. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35392. }
  35393. else {
  35394. multiMaterial.subMaterials.push(null);
  35395. }
  35396. }
  35397. return multiMaterial;
  35398. };
  35399. /**
  35400. * Creates a material from parsed material data
  35401. * @param parsedMaterial defines parsed material data
  35402. * @param scene defines the hosting scene
  35403. * @param rootUrl defines the root URL to use to load textures
  35404. * @returns a new material
  35405. */
  35406. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35407. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35408. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35409. }
  35410. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35411. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35412. if (!BABYLON.LegacyPBRMaterial) {
  35413. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35414. return;
  35415. }
  35416. }
  35417. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35418. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35419. };
  35420. // Triangle views
  35421. Material._TriangleFillMode = 0;
  35422. Material._WireFrameFillMode = 1;
  35423. Material._PointFillMode = 2;
  35424. // Draw modes
  35425. Material._PointListDrawMode = 3;
  35426. Material._LineListDrawMode = 4;
  35427. Material._LineLoopDrawMode = 5;
  35428. Material._LineStripDrawMode = 6;
  35429. Material._TriangleStripDrawMode = 7;
  35430. Material._TriangleFanDrawMode = 8;
  35431. /**
  35432. * Stores the clock-wise side orientation
  35433. */
  35434. Material._ClockWiseSideOrientation = 0;
  35435. /**
  35436. * Stores the counter clock-wise side orientation
  35437. */
  35438. Material._CounterClockWiseSideOrientation = 1;
  35439. /**
  35440. * The dirty texture flag value
  35441. */
  35442. Material._TextureDirtyFlag = 1;
  35443. /**
  35444. * The dirty light flag value
  35445. */
  35446. Material._LightDirtyFlag = 2;
  35447. /**
  35448. * The dirty fresnel flag value
  35449. */
  35450. Material._FresnelDirtyFlag = 4;
  35451. /**
  35452. * The dirty attribute flag value
  35453. */
  35454. Material._AttributesDirtyFlag = 8;
  35455. /**
  35456. * The dirty misc flag value
  35457. */
  35458. Material._MiscDirtyFlag = 16;
  35459. __decorate([
  35460. BABYLON.serialize()
  35461. ], Material.prototype, "id", void 0);
  35462. __decorate([
  35463. BABYLON.serialize()
  35464. ], Material.prototype, "uniqueId", void 0);
  35465. __decorate([
  35466. BABYLON.serialize()
  35467. ], Material.prototype, "name", void 0);
  35468. __decorate([
  35469. BABYLON.serialize()
  35470. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35471. __decorate([
  35472. BABYLON.serialize()
  35473. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35474. __decorate([
  35475. BABYLON.serialize()
  35476. ], Material.prototype, "state", void 0);
  35477. __decorate([
  35478. BABYLON.serialize("alpha")
  35479. ], Material.prototype, "_alpha", void 0);
  35480. __decorate([
  35481. BABYLON.serialize("backFaceCulling")
  35482. ], Material.prototype, "_backFaceCulling", void 0);
  35483. __decorate([
  35484. BABYLON.serialize()
  35485. ], Material.prototype, "sideOrientation", void 0);
  35486. __decorate([
  35487. BABYLON.serialize("alphaMode")
  35488. ], Material.prototype, "_alphaMode", void 0);
  35489. __decorate([
  35490. BABYLON.serialize()
  35491. ], Material.prototype, "_needDepthPrePass", void 0);
  35492. __decorate([
  35493. BABYLON.serialize()
  35494. ], Material.prototype, "disableDepthWrite", void 0);
  35495. __decorate([
  35496. BABYLON.serialize()
  35497. ], Material.prototype, "forceDepthWrite", void 0);
  35498. __decorate([
  35499. BABYLON.serialize()
  35500. ], Material.prototype, "separateCullingPass", void 0);
  35501. __decorate([
  35502. BABYLON.serialize("fogEnabled")
  35503. ], Material.prototype, "_fogEnabled", void 0);
  35504. __decorate([
  35505. BABYLON.serialize()
  35506. ], Material.prototype, "pointSize", void 0);
  35507. __decorate([
  35508. BABYLON.serialize()
  35509. ], Material.prototype, "zOffset", void 0);
  35510. __decorate([
  35511. BABYLON.serialize()
  35512. ], Material.prototype, "wireframe", null);
  35513. __decorate([
  35514. BABYLON.serialize()
  35515. ], Material.prototype, "pointsCloud", null);
  35516. __decorate([
  35517. BABYLON.serialize()
  35518. ], Material.prototype, "fillMode", null);
  35519. return Material;
  35520. }());
  35521. BABYLON.Material = Material;
  35522. })(BABYLON || (BABYLON = {}));
  35523. //# sourceMappingURL=babylon.material.js.map
  35524. var BABYLON;
  35525. (function (BABYLON) {
  35526. var UniformBuffer = /** @class */ (function () {
  35527. /**
  35528. * Uniform buffer objects.
  35529. *
  35530. * Handles blocks of uniform on the GPU.
  35531. *
  35532. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35533. *
  35534. * For more information, please refer to :
  35535. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35536. */
  35537. function UniformBuffer(engine, data, dynamic) {
  35538. this._engine = engine;
  35539. this._noUBO = !engine.supportsUniformBuffers;
  35540. this._dynamic = dynamic;
  35541. this._data = data || [];
  35542. this._uniformLocations = {};
  35543. this._uniformSizes = {};
  35544. this._uniformLocationPointer = 0;
  35545. this._needSync = false;
  35546. if (this._noUBO) {
  35547. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35548. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35549. this.updateFloat = this._updateFloatForEffect;
  35550. this.updateFloat2 = this._updateFloat2ForEffect;
  35551. this.updateFloat3 = this._updateFloat3ForEffect;
  35552. this.updateFloat4 = this._updateFloat4ForEffect;
  35553. this.updateMatrix = this._updateMatrixForEffect;
  35554. this.updateVector3 = this._updateVector3ForEffect;
  35555. this.updateVector4 = this._updateVector4ForEffect;
  35556. this.updateColor3 = this._updateColor3ForEffect;
  35557. this.updateColor4 = this._updateColor4ForEffect;
  35558. }
  35559. else {
  35560. this._engine._uniformBuffers.push(this);
  35561. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35562. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35563. this.updateFloat = this._updateFloatForUniform;
  35564. this.updateFloat2 = this._updateFloat2ForUniform;
  35565. this.updateFloat3 = this._updateFloat3ForUniform;
  35566. this.updateFloat4 = this._updateFloat4ForUniform;
  35567. this.updateMatrix = this._updateMatrixForUniform;
  35568. this.updateVector3 = this._updateVector3ForUniform;
  35569. this.updateVector4 = this._updateVector4ForUniform;
  35570. this.updateColor3 = this._updateColor3ForUniform;
  35571. this.updateColor4 = this._updateColor4ForUniform;
  35572. }
  35573. }
  35574. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35575. // Properties
  35576. /**
  35577. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35578. * or just falling back on setUniformXXX calls.
  35579. */
  35580. get: function () {
  35581. return !this._noUBO;
  35582. },
  35583. enumerable: true,
  35584. configurable: true
  35585. });
  35586. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35587. /**
  35588. * Indicates if the WebGL underlying uniform buffer is in sync
  35589. * with the javascript cache data.
  35590. */
  35591. get: function () {
  35592. return !this._needSync;
  35593. },
  35594. enumerable: true,
  35595. configurable: true
  35596. });
  35597. /**
  35598. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35599. * Also, a dynamic UniformBuffer will disable cache verification and always
  35600. * update the underlying WebGL uniform buffer to the GPU.
  35601. */
  35602. UniformBuffer.prototype.isDynamic = function () {
  35603. return this._dynamic !== undefined;
  35604. };
  35605. /**
  35606. * The data cache on JS side.
  35607. */
  35608. UniformBuffer.prototype.getData = function () {
  35609. return this._bufferData;
  35610. };
  35611. /**
  35612. * The underlying WebGL Uniform buffer.
  35613. */
  35614. UniformBuffer.prototype.getBuffer = function () {
  35615. return this._buffer;
  35616. };
  35617. /**
  35618. * std140 layout specifies how to align data within an UBO structure.
  35619. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35620. * for specs.
  35621. */
  35622. UniformBuffer.prototype._fillAlignment = function (size) {
  35623. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35624. // and 4x4 matrices
  35625. // TODO : change if other types are used
  35626. var alignment;
  35627. if (size <= 2) {
  35628. alignment = size;
  35629. }
  35630. else {
  35631. alignment = 4;
  35632. }
  35633. if ((this._uniformLocationPointer % alignment) !== 0) {
  35634. var oldPointer = this._uniformLocationPointer;
  35635. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35636. var diff = this._uniformLocationPointer - oldPointer;
  35637. for (var i = 0; i < diff; i++) {
  35638. this._data.push(0);
  35639. }
  35640. }
  35641. };
  35642. /**
  35643. * Adds an uniform in the buffer.
  35644. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35645. * for the layout to be correct !
  35646. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35647. * @param {number|number[]} size Data size, or data directly.
  35648. */
  35649. UniformBuffer.prototype.addUniform = function (name, size) {
  35650. if (this._noUBO) {
  35651. return;
  35652. }
  35653. if (this._uniformLocations[name] !== undefined) {
  35654. // Already existing uniform
  35655. return;
  35656. }
  35657. // This function must be called in the order of the shader layout !
  35658. // size can be the size of the uniform, or data directly
  35659. var data;
  35660. if (size instanceof Array) {
  35661. data = size;
  35662. size = data.length;
  35663. }
  35664. else {
  35665. size = size;
  35666. data = [];
  35667. // Fill with zeros
  35668. for (var i = 0; i < size; i++) {
  35669. data.push(0);
  35670. }
  35671. }
  35672. this._fillAlignment(size);
  35673. this._uniformSizes[name] = size;
  35674. this._uniformLocations[name] = this._uniformLocationPointer;
  35675. this._uniformLocationPointer += size;
  35676. for (var i = 0; i < size; i++) {
  35677. this._data.push(data[i]);
  35678. }
  35679. this._needSync = true;
  35680. };
  35681. /**
  35682. * Wrapper for addUniform.
  35683. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35684. * @param {Matrix} mat A 4x4 matrix.
  35685. */
  35686. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35687. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35688. };
  35689. /**
  35690. * Wrapper for addUniform.
  35691. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35692. * @param {number} x
  35693. * @param {number} y
  35694. */
  35695. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35696. var temp = [x, y];
  35697. this.addUniform(name, temp);
  35698. };
  35699. /**
  35700. * Wrapper for addUniform.
  35701. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35702. * @param {number} x
  35703. * @param {number} y
  35704. * @param {number} z
  35705. */
  35706. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35707. var temp = [x, y, z];
  35708. this.addUniform(name, temp);
  35709. };
  35710. /**
  35711. * Wrapper for addUniform.
  35712. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35713. * @param {Color3} color
  35714. */
  35715. UniformBuffer.prototype.addColor3 = function (name, color) {
  35716. var temp = new Array();
  35717. color.toArray(temp);
  35718. this.addUniform(name, temp);
  35719. };
  35720. /**
  35721. * Wrapper for addUniform.
  35722. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35723. * @param {Color3} color
  35724. * @param {number} alpha
  35725. */
  35726. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35727. var temp = new Array();
  35728. color.toArray(temp);
  35729. temp.push(alpha);
  35730. this.addUniform(name, temp);
  35731. };
  35732. /**
  35733. * Wrapper for addUniform.
  35734. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35735. * @param {Vector3} vector
  35736. */
  35737. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35738. var temp = new Array();
  35739. vector.toArray(temp);
  35740. this.addUniform(name, temp);
  35741. };
  35742. /**
  35743. * Wrapper for addUniform.
  35744. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35745. */
  35746. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35747. this.addUniform(name, 12);
  35748. };
  35749. /**
  35750. * Wrapper for addUniform.
  35751. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35752. */
  35753. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35754. this.addUniform(name, 8);
  35755. };
  35756. /**
  35757. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35758. */
  35759. UniformBuffer.prototype.create = function () {
  35760. if (this._noUBO) {
  35761. return;
  35762. }
  35763. if (this._buffer) {
  35764. return; // nothing to do
  35765. }
  35766. // See spec, alignment must be filled as a vec4
  35767. this._fillAlignment(4);
  35768. this._bufferData = new Float32Array(this._data);
  35769. this._rebuild();
  35770. this._needSync = true;
  35771. };
  35772. UniformBuffer.prototype._rebuild = function () {
  35773. if (this._noUBO) {
  35774. return;
  35775. }
  35776. if (this._dynamic) {
  35777. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35778. }
  35779. else {
  35780. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35781. }
  35782. };
  35783. /**
  35784. * Updates the WebGL Uniform Buffer on the GPU.
  35785. * If the `dynamic` flag is set to true, no cache comparison is done.
  35786. * Otherwise, the buffer will be updated only if the cache differs.
  35787. */
  35788. UniformBuffer.prototype.update = function () {
  35789. if (!this._buffer) {
  35790. this.create();
  35791. return;
  35792. }
  35793. if (!this._dynamic && !this._needSync) {
  35794. return;
  35795. }
  35796. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35797. this._needSync = false;
  35798. };
  35799. /**
  35800. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35801. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35802. * @param {number[]|Float32Array} data Flattened data
  35803. * @param {number} size Size of the data.
  35804. */
  35805. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35806. var location = this._uniformLocations[uniformName];
  35807. if (location === undefined) {
  35808. if (this._buffer) {
  35809. // Cannot add an uniform if the buffer is already created
  35810. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35811. return;
  35812. }
  35813. this.addUniform(uniformName, size);
  35814. location = this._uniformLocations[uniformName];
  35815. }
  35816. if (!this._buffer) {
  35817. this.create();
  35818. }
  35819. if (!this._dynamic) {
  35820. // Cache for static uniform buffers
  35821. var changed = false;
  35822. for (var i = 0; i < size; i++) {
  35823. if (this._bufferData[location + i] !== data[i]) {
  35824. changed = true;
  35825. this._bufferData[location + i] = data[i];
  35826. }
  35827. }
  35828. this._needSync = this._needSync || changed;
  35829. }
  35830. else {
  35831. // No cache for dynamic
  35832. for (var i = 0; i < size; i++) {
  35833. this._bufferData[location + i] = data[i];
  35834. }
  35835. }
  35836. };
  35837. // Update methods
  35838. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35839. // To match std140, matrix must be realigned
  35840. for (var i = 0; i < 3; i++) {
  35841. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35842. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35843. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35844. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35845. }
  35846. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35847. };
  35848. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35849. this._currentEffect.setMatrix3x3(name, matrix);
  35850. };
  35851. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35852. this._currentEffect.setMatrix2x2(name, matrix);
  35853. };
  35854. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35855. // To match std140, matrix must be realigned
  35856. for (var i = 0; i < 2; i++) {
  35857. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35858. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35859. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35860. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35861. }
  35862. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35863. };
  35864. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35865. this._currentEffect.setFloat(name, x);
  35866. };
  35867. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35868. UniformBuffer._tempBuffer[0] = x;
  35869. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35870. };
  35871. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35872. if (suffix === void 0) { suffix = ""; }
  35873. this._currentEffect.setFloat2(name + suffix, x, y);
  35874. };
  35875. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35876. if (suffix === void 0) { suffix = ""; }
  35877. UniformBuffer._tempBuffer[0] = x;
  35878. UniformBuffer._tempBuffer[1] = y;
  35879. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35880. };
  35881. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35882. if (suffix === void 0) { suffix = ""; }
  35883. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35884. };
  35885. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35886. if (suffix === void 0) { suffix = ""; }
  35887. UniformBuffer._tempBuffer[0] = x;
  35888. UniformBuffer._tempBuffer[1] = y;
  35889. UniformBuffer._tempBuffer[2] = z;
  35890. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35891. };
  35892. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35893. if (suffix === void 0) { suffix = ""; }
  35894. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35895. };
  35896. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35897. if (suffix === void 0) { suffix = ""; }
  35898. UniformBuffer._tempBuffer[0] = x;
  35899. UniformBuffer._tempBuffer[1] = y;
  35900. UniformBuffer._tempBuffer[2] = z;
  35901. UniformBuffer._tempBuffer[3] = w;
  35902. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35903. };
  35904. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35905. this._currentEffect.setMatrix(name, mat);
  35906. };
  35907. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35908. this.updateUniform(name, mat.toArray(), 16);
  35909. };
  35910. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35911. this._currentEffect.setVector3(name, vector);
  35912. };
  35913. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35914. vector.toArray(UniformBuffer._tempBuffer);
  35915. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35916. };
  35917. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35918. this._currentEffect.setVector4(name, vector);
  35919. };
  35920. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35921. vector.toArray(UniformBuffer._tempBuffer);
  35922. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35923. };
  35924. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35925. if (suffix === void 0) { suffix = ""; }
  35926. this._currentEffect.setColor3(name + suffix, color);
  35927. };
  35928. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35929. if (suffix === void 0) { suffix = ""; }
  35930. color.toArray(UniformBuffer._tempBuffer);
  35931. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35932. };
  35933. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35934. if (suffix === void 0) { suffix = ""; }
  35935. this._currentEffect.setColor4(name + suffix, color, alpha);
  35936. };
  35937. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35938. if (suffix === void 0) { suffix = ""; }
  35939. color.toArray(UniformBuffer._tempBuffer);
  35940. UniformBuffer._tempBuffer[3] = alpha;
  35941. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35942. };
  35943. /**
  35944. * Sets a sampler uniform on the effect.
  35945. * @param {string} name Name of the sampler.
  35946. * @param {Texture} texture
  35947. */
  35948. UniformBuffer.prototype.setTexture = function (name, texture) {
  35949. this._currentEffect.setTexture(name, texture);
  35950. };
  35951. /**
  35952. * Directly updates the value of the uniform in the cache AND on the GPU.
  35953. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35954. * @param {number[]|Float32Array} data Flattened data
  35955. */
  35956. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35957. this.updateUniform(uniformName, data, data.length);
  35958. this.update();
  35959. };
  35960. /**
  35961. * Binds this uniform buffer to an effect.
  35962. * @param {Effect} effect
  35963. * @param {string} name Name of the uniform block in the shader.
  35964. */
  35965. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35966. this._currentEffect = effect;
  35967. if (this._noUBO || !this._buffer) {
  35968. return;
  35969. }
  35970. effect.bindUniformBuffer(this._buffer, name);
  35971. };
  35972. /**
  35973. * Disposes the uniform buffer.
  35974. */
  35975. UniformBuffer.prototype.dispose = function () {
  35976. if (this._noUBO) {
  35977. return;
  35978. }
  35979. var index = this._engine._uniformBuffers.indexOf(this);
  35980. if (index !== -1) {
  35981. this._engine._uniformBuffers.splice(index, 1);
  35982. }
  35983. if (!this._buffer) {
  35984. return;
  35985. }
  35986. if (this._engine._releaseBuffer(this._buffer)) {
  35987. this._buffer = null;
  35988. }
  35989. };
  35990. // Pool for avoiding memory leaks
  35991. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35992. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35993. return UniformBuffer;
  35994. }());
  35995. BABYLON.UniformBuffer = UniformBuffer;
  35996. })(BABYLON || (BABYLON = {}));
  35997. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35998. var BABYLON;
  35999. (function (BABYLON) {
  36000. /**
  36001. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36002. */
  36003. var VertexData = /** @class */ (function () {
  36004. function VertexData() {
  36005. }
  36006. /**
  36007. * Uses the passed data array to set the set the values for the specified kind of data
  36008. * @param data a linear array of floating numbers
  36009. * @param kind the type of data that is being set, eg positions, colors etc
  36010. */
  36011. VertexData.prototype.set = function (data, kind) {
  36012. switch (kind) {
  36013. case BABYLON.VertexBuffer.PositionKind:
  36014. this.positions = data;
  36015. break;
  36016. case BABYLON.VertexBuffer.NormalKind:
  36017. this.normals = data;
  36018. break;
  36019. case BABYLON.VertexBuffer.TangentKind:
  36020. this.tangents = data;
  36021. break;
  36022. case BABYLON.VertexBuffer.UVKind:
  36023. this.uvs = data;
  36024. break;
  36025. case BABYLON.VertexBuffer.UV2Kind:
  36026. this.uvs2 = data;
  36027. break;
  36028. case BABYLON.VertexBuffer.UV3Kind:
  36029. this.uvs3 = data;
  36030. break;
  36031. case BABYLON.VertexBuffer.UV4Kind:
  36032. this.uvs4 = data;
  36033. break;
  36034. case BABYLON.VertexBuffer.UV5Kind:
  36035. this.uvs5 = data;
  36036. break;
  36037. case BABYLON.VertexBuffer.UV6Kind:
  36038. this.uvs6 = data;
  36039. break;
  36040. case BABYLON.VertexBuffer.ColorKind:
  36041. this.colors = data;
  36042. break;
  36043. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36044. this.matricesIndices = data;
  36045. break;
  36046. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36047. this.matricesWeights = data;
  36048. break;
  36049. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36050. this.matricesIndicesExtra = data;
  36051. break;
  36052. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36053. this.matricesWeightsExtra = data;
  36054. break;
  36055. }
  36056. };
  36057. /**
  36058. * Associates the vertexData to the passed Mesh.
  36059. * Sets it as updatable or not (default `false`)
  36060. * @param mesh the mesh the vertexData is applied to
  36061. * @param updatable when used and having the value true allows new data to update the vertexData
  36062. * @returns the VertexData
  36063. */
  36064. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36065. this._applyTo(mesh, updatable);
  36066. return this;
  36067. };
  36068. /**
  36069. * Associates the vertexData to the passed Geometry.
  36070. * Sets it as updatable or not (default `false`)
  36071. * @param geometry the geometry the vertexData is applied to
  36072. * @param updatable when used and having the value true allows new data to update the vertexData
  36073. * @returns VertexData
  36074. */
  36075. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36076. this._applyTo(geometry, updatable);
  36077. return this;
  36078. };
  36079. /**
  36080. * Updates the associated mesh
  36081. * @param mesh the mesh to be updated
  36082. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36083. * @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
  36084. * @returns VertexData
  36085. */
  36086. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36087. this._update(mesh);
  36088. return this;
  36089. };
  36090. /**
  36091. * Updates the associated geometry
  36092. * @param geometry the geometry to be updated
  36093. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36094. * @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
  36095. * @returns VertexData.
  36096. */
  36097. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36098. this._update(geometry);
  36099. return this;
  36100. };
  36101. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36102. if (updatable === void 0) { updatable = false; }
  36103. if (this.positions) {
  36104. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36105. }
  36106. if (this.normals) {
  36107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36108. }
  36109. if (this.tangents) {
  36110. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36111. }
  36112. if (this.uvs) {
  36113. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36114. }
  36115. if (this.uvs2) {
  36116. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36117. }
  36118. if (this.uvs3) {
  36119. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36120. }
  36121. if (this.uvs4) {
  36122. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36123. }
  36124. if (this.uvs5) {
  36125. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36126. }
  36127. if (this.uvs6) {
  36128. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36129. }
  36130. if (this.colors) {
  36131. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36132. }
  36133. if (this.matricesIndices) {
  36134. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36135. }
  36136. if (this.matricesWeights) {
  36137. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36138. }
  36139. if (this.matricesIndicesExtra) {
  36140. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36141. }
  36142. if (this.matricesWeightsExtra) {
  36143. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36144. }
  36145. if (this.indices) {
  36146. meshOrGeometry.setIndices(this.indices, null, updatable);
  36147. }
  36148. else {
  36149. meshOrGeometry.setIndices([], null);
  36150. }
  36151. return this;
  36152. };
  36153. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36154. if (this.positions) {
  36155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36156. }
  36157. if (this.normals) {
  36158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36159. }
  36160. if (this.tangents) {
  36161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36162. }
  36163. if (this.uvs) {
  36164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36165. }
  36166. if (this.uvs2) {
  36167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36168. }
  36169. if (this.uvs3) {
  36170. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36171. }
  36172. if (this.uvs4) {
  36173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36174. }
  36175. if (this.uvs5) {
  36176. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36177. }
  36178. if (this.uvs6) {
  36179. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36180. }
  36181. if (this.colors) {
  36182. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36183. }
  36184. if (this.matricesIndices) {
  36185. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36186. }
  36187. if (this.matricesWeights) {
  36188. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36189. }
  36190. if (this.matricesIndicesExtra) {
  36191. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36192. }
  36193. if (this.matricesWeightsExtra) {
  36194. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36195. }
  36196. if (this.indices) {
  36197. meshOrGeometry.setIndices(this.indices, null);
  36198. }
  36199. return this;
  36200. };
  36201. /**
  36202. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36203. * @param matrix the transforming matrix
  36204. * @returns the VertexData
  36205. */
  36206. VertexData.prototype.transform = function (matrix) {
  36207. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36208. var transformed = BABYLON.Vector3.Zero();
  36209. var index;
  36210. if (this.positions) {
  36211. var position = BABYLON.Vector3.Zero();
  36212. for (index = 0; index < this.positions.length; index += 3) {
  36213. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36214. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36215. this.positions[index] = transformed.x;
  36216. this.positions[index + 1] = transformed.y;
  36217. this.positions[index + 2] = transformed.z;
  36218. }
  36219. }
  36220. if (this.normals) {
  36221. var normal = BABYLON.Vector3.Zero();
  36222. for (index = 0; index < this.normals.length; index += 3) {
  36223. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36224. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36225. this.normals[index] = transformed.x;
  36226. this.normals[index + 1] = transformed.y;
  36227. this.normals[index + 2] = transformed.z;
  36228. }
  36229. }
  36230. if (this.tangents) {
  36231. var tangent = BABYLON.Vector4.Zero();
  36232. var tangentTransformed = BABYLON.Vector4.Zero();
  36233. for (index = 0; index < this.tangents.length; index += 4) {
  36234. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36235. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36236. this.tangents[index] = tangentTransformed.x;
  36237. this.tangents[index + 1] = tangentTransformed.y;
  36238. this.tangents[index + 2] = tangentTransformed.z;
  36239. this.tangents[index + 3] = tangentTransformed.w;
  36240. }
  36241. }
  36242. if (flip && this.indices) {
  36243. for (index = 0; index < this.indices.length; index += 3) {
  36244. var tmp = this.indices[index + 1];
  36245. this.indices[index + 1] = this.indices[index + 2];
  36246. this.indices[index + 2] = tmp;
  36247. }
  36248. }
  36249. return this;
  36250. };
  36251. /**
  36252. * Merges the passed VertexData into the current one
  36253. * @param other the VertexData to be merged into the current one
  36254. * @returns the modified VertexData
  36255. */
  36256. VertexData.prototype.merge = function (other) {
  36257. this._validate();
  36258. other._validate();
  36259. if (!this.normals !== !other.normals ||
  36260. !this.tangents !== !other.tangents ||
  36261. !this.uvs !== !other.uvs ||
  36262. !this.uvs2 !== !other.uvs2 ||
  36263. !this.uvs3 !== !other.uvs3 ||
  36264. !this.uvs4 !== !other.uvs4 ||
  36265. !this.uvs5 !== !other.uvs5 ||
  36266. !this.uvs6 !== !other.uvs6 ||
  36267. !this.colors !== !other.colors ||
  36268. !this.matricesIndices !== !other.matricesIndices ||
  36269. !this.matricesWeights !== !other.matricesWeights ||
  36270. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36271. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36272. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36273. }
  36274. if (other.indices) {
  36275. if (!this.indices) {
  36276. this.indices = [];
  36277. }
  36278. var offset = this.positions ? this.positions.length / 3 : 0;
  36279. for (var index = 0; index < other.indices.length; index++) {
  36280. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36281. this.indices.push(other.indices[index] + offset);
  36282. }
  36283. }
  36284. this.positions = this._mergeElement(this.positions, other.positions);
  36285. this.normals = this._mergeElement(this.normals, other.normals);
  36286. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36287. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36288. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36289. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36290. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36291. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36292. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36293. this.colors = this._mergeElement(this.colors, other.colors);
  36294. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36295. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36296. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36297. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36298. return this;
  36299. };
  36300. VertexData.prototype._mergeElement = function (source, other) {
  36301. if (!source) {
  36302. return other;
  36303. }
  36304. if (!other) {
  36305. return source;
  36306. }
  36307. var len = other.length + source.length;
  36308. var isSrcTypedArray = source instanceof Float32Array;
  36309. var isOthTypedArray = other instanceof Float32Array;
  36310. // use non-loop method when the source is Float32Array
  36311. if (isSrcTypedArray) {
  36312. var ret32 = new Float32Array(len);
  36313. ret32.set(source);
  36314. ret32.set(other, source.length);
  36315. return ret32;
  36316. // source is number[], when other is also use concat
  36317. }
  36318. else if (!isOthTypedArray) {
  36319. return source.concat(other);
  36320. // source is a number[], but other is a Float32Array, loop required
  36321. }
  36322. else {
  36323. var ret = source.slice(0); // copy source to a separate array
  36324. for (var i = 0, len = other.length; i < len; i++) {
  36325. ret.push(other[i]);
  36326. }
  36327. return ret;
  36328. }
  36329. };
  36330. VertexData.prototype._validate = function () {
  36331. if (!this.positions) {
  36332. throw new Error("Positions are required");
  36333. }
  36334. var getElementCount = function (kind, values) {
  36335. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36336. if ((values.length % stride) !== 0) {
  36337. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36338. }
  36339. return values.length / stride;
  36340. };
  36341. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36342. var validateElementCount = function (kind, values) {
  36343. var elementCount = getElementCount(kind, values);
  36344. if (elementCount !== positionsElementCount) {
  36345. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36346. }
  36347. };
  36348. if (this.normals)
  36349. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36350. if (this.tangents)
  36351. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36352. if (this.uvs)
  36353. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36354. if (this.uvs2)
  36355. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36356. if (this.uvs3)
  36357. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36358. if (this.uvs4)
  36359. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36360. if (this.uvs5)
  36361. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36362. if (this.uvs6)
  36363. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36364. if (this.colors)
  36365. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36366. if (this.matricesIndices)
  36367. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36368. if (this.matricesWeights)
  36369. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36370. if (this.matricesIndicesExtra)
  36371. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36372. if (this.matricesWeightsExtra)
  36373. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36374. };
  36375. /**
  36376. * Serializes the VertexData
  36377. * @returns a serialized object
  36378. */
  36379. VertexData.prototype.serialize = function () {
  36380. var serializationObject = this.serialize();
  36381. if (this.positions) {
  36382. serializationObject.positions = this.positions;
  36383. }
  36384. if (this.normals) {
  36385. serializationObject.normals = this.normals;
  36386. }
  36387. if (this.tangents) {
  36388. serializationObject.tangents = this.tangents;
  36389. }
  36390. if (this.uvs) {
  36391. serializationObject.uvs = this.uvs;
  36392. }
  36393. if (this.uvs2) {
  36394. serializationObject.uvs2 = this.uvs2;
  36395. }
  36396. if (this.uvs3) {
  36397. serializationObject.uvs3 = this.uvs3;
  36398. }
  36399. if (this.uvs4) {
  36400. serializationObject.uvs4 = this.uvs4;
  36401. }
  36402. if (this.uvs5) {
  36403. serializationObject.uvs5 = this.uvs5;
  36404. }
  36405. if (this.uvs6) {
  36406. serializationObject.uvs6 = this.uvs6;
  36407. }
  36408. if (this.colors) {
  36409. serializationObject.colors = this.colors;
  36410. }
  36411. if (this.matricesIndices) {
  36412. serializationObject.matricesIndices = this.matricesIndices;
  36413. serializationObject.matricesIndices._isExpanded = true;
  36414. }
  36415. if (this.matricesWeights) {
  36416. serializationObject.matricesWeights = this.matricesWeights;
  36417. }
  36418. if (this.matricesIndicesExtra) {
  36419. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36420. serializationObject.matricesIndicesExtra._isExpanded = true;
  36421. }
  36422. if (this.matricesWeightsExtra) {
  36423. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36424. }
  36425. serializationObject.indices = this.indices;
  36426. return serializationObject;
  36427. };
  36428. // Statics
  36429. /**
  36430. * Extracts the vertexData from a mesh
  36431. * @param mesh the mesh from which to extract the VertexData
  36432. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36433. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36434. * @returns the object VertexData associated to the passed mesh
  36435. */
  36436. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36437. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36438. };
  36439. /**
  36440. * Extracts the vertexData from the geometry
  36441. * @param geometry the geometry from which to extract the VertexData
  36442. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36443. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36444. * @returns the object VertexData associated to the passed mesh
  36445. */
  36446. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36447. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36448. };
  36449. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36450. var result = new VertexData();
  36451. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36452. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36453. }
  36454. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36455. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36456. }
  36457. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36458. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36459. }
  36460. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36461. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36462. }
  36463. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36464. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36465. }
  36466. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36467. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36468. }
  36469. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36470. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36471. }
  36472. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36473. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36474. }
  36475. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36476. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36477. }
  36478. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36479. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36480. }
  36481. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36482. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36483. }
  36484. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36485. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36486. }
  36487. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36488. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36489. }
  36490. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36491. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36492. }
  36493. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36494. return result;
  36495. };
  36496. /**
  36497. * Creates the VertexData for a Ribbon
  36498. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36499. * * pathArray array of paths, each of which an array of successive Vector3
  36500. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36501. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36502. * * 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
  36503. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36504. * * 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)
  36505. * * 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)
  36506. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36507. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36508. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36509. * @returns the VertexData of the ribbon
  36510. */
  36511. VertexData.CreateRibbon = function (options) {
  36512. var pathArray = options.pathArray;
  36513. var closeArray = options.closeArray || false;
  36514. var closePath = options.closePath || false;
  36515. var invertUV = options.invertUV || false;
  36516. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36517. var offset = options.offset || defaultOffset;
  36518. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36519. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36520. var customUV = options.uvs;
  36521. var customColors = options.colors;
  36522. var positions = [];
  36523. var indices = [];
  36524. var normals = [];
  36525. var uvs = [];
  36526. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36527. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36528. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36529. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36530. var minlg; // minimal length among all paths from pathArray
  36531. var lg = []; // array of path lengths : nb of vertex per path
  36532. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36533. var p; // path iterator
  36534. var i; // point iterator
  36535. var j; // point iterator
  36536. // if single path in pathArray
  36537. if (pathArray.length < 2) {
  36538. var ar1 = [];
  36539. var ar2 = [];
  36540. for (i = 0; i < pathArray[0].length - offset; i++) {
  36541. ar1.push(pathArray[0][i]);
  36542. ar2.push(pathArray[0][i + offset]);
  36543. }
  36544. pathArray = [ar1, ar2];
  36545. }
  36546. // positions and horizontal distances (u)
  36547. var idc = 0;
  36548. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36549. var path;
  36550. var l;
  36551. minlg = pathArray[0].length;
  36552. var vectlg;
  36553. var dist;
  36554. for (p = 0; p < pathArray.length; p++) {
  36555. uTotalDistance[p] = 0;
  36556. us[p] = [0];
  36557. path = pathArray[p];
  36558. l = path.length;
  36559. minlg = (minlg < l) ? minlg : l;
  36560. j = 0;
  36561. while (j < l) {
  36562. positions.push(path[j].x, path[j].y, path[j].z);
  36563. if (j > 0) {
  36564. vectlg = path[j].subtract(path[j - 1]).length();
  36565. dist = vectlg + uTotalDistance[p];
  36566. us[p].push(dist);
  36567. uTotalDistance[p] = dist;
  36568. }
  36569. j++;
  36570. }
  36571. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36572. j--;
  36573. positions.push(path[0].x, path[0].y, path[0].z);
  36574. vectlg = path[j].subtract(path[0]).length();
  36575. dist = vectlg + uTotalDistance[p];
  36576. us[p].push(dist);
  36577. uTotalDistance[p] = dist;
  36578. }
  36579. lg[p] = l + closePathCorr;
  36580. idx[p] = idc;
  36581. idc += (l + closePathCorr);
  36582. }
  36583. // vertical distances (v)
  36584. var path1;
  36585. var path2;
  36586. var vertex1 = null;
  36587. var vertex2 = null;
  36588. for (i = 0; i < minlg + closePathCorr; i++) {
  36589. vTotalDistance[i] = 0;
  36590. vs[i] = [0];
  36591. for (p = 0; p < pathArray.length - 1; p++) {
  36592. path1 = pathArray[p];
  36593. path2 = pathArray[p + 1];
  36594. if (i === minlg) { // closePath
  36595. vertex1 = path1[0];
  36596. vertex2 = path2[0];
  36597. }
  36598. else {
  36599. vertex1 = path1[i];
  36600. vertex2 = path2[i];
  36601. }
  36602. vectlg = vertex2.subtract(vertex1).length();
  36603. dist = vectlg + vTotalDistance[i];
  36604. vs[i].push(dist);
  36605. vTotalDistance[i] = dist;
  36606. }
  36607. if (closeArray && vertex2 && vertex1) {
  36608. path1 = pathArray[p];
  36609. path2 = pathArray[0];
  36610. if (i === minlg) { // closePath
  36611. vertex2 = path2[0];
  36612. }
  36613. vectlg = vertex2.subtract(vertex1).length();
  36614. dist = vectlg + vTotalDistance[i];
  36615. vTotalDistance[i] = dist;
  36616. }
  36617. }
  36618. // uvs
  36619. var u;
  36620. var v;
  36621. if (customUV) {
  36622. for (p = 0; p < customUV.length; p++) {
  36623. uvs.push(customUV[p].x, customUV[p].y);
  36624. }
  36625. }
  36626. else {
  36627. for (p = 0; p < pathArray.length; p++) {
  36628. for (i = 0; i < minlg + closePathCorr; i++) {
  36629. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36630. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36631. if (invertUV) {
  36632. uvs.push(v, u);
  36633. }
  36634. else {
  36635. uvs.push(u, v);
  36636. }
  36637. }
  36638. }
  36639. }
  36640. // indices
  36641. p = 0; // path index
  36642. var pi = 0; // positions array index
  36643. var l1 = lg[p] - 1; // path1 length
  36644. var l2 = lg[p + 1] - 1; // path2 length
  36645. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36646. var shft = idx[1] - idx[0]; // shift
  36647. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36648. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36649. // 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
  36650. indices.push(pi, pi + shft, pi + 1);
  36651. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36652. pi += 1;
  36653. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36654. p++;
  36655. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36656. shft = idx[0] - idx[p];
  36657. l1 = lg[p] - 1;
  36658. l2 = lg[0] - 1;
  36659. }
  36660. else {
  36661. shft = idx[p + 1] - idx[p];
  36662. l1 = lg[p] - 1;
  36663. l2 = lg[p + 1] - 1;
  36664. }
  36665. pi = idx[p];
  36666. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36667. }
  36668. }
  36669. // normals
  36670. VertexData.ComputeNormals(positions, indices, normals);
  36671. if (closePath) { // update both the first and last vertex normals to their average value
  36672. var indexFirst = 0;
  36673. var indexLast = 0;
  36674. for (p = 0; p < pathArray.length; p++) {
  36675. indexFirst = idx[p] * 3;
  36676. if (p + 1 < pathArray.length) {
  36677. indexLast = (idx[p + 1] - 1) * 3;
  36678. }
  36679. else {
  36680. indexLast = normals.length - 3;
  36681. }
  36682. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36683. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36684. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36685. normals[indexLast] = normals[indexFirst];
  36686. normals[indexLast + 1] = normals[indexFirst + 1];
  36687. normals[indexLast + 2] = normals[indexFirst + 2];
  36688. }
  36689. }
  36690. // sides
  36691. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36692. // Colors
  36693. var colors = null;
  36694. if (customColors) {
  36695. colors = new Float32Array(customColors.length * 4);
  36696. for (var c = 0; c < customColors.length; c++) {
  36697. colors[c * 4] = customColors[c].r;
  36698. colors[c * 4 + 1] = customColors[c].g;
  36699. colors[c * 4 + 2] = customColors[c].b;
  36700. colors[c * 4 + 3] = customColors[c].a;
  36701. }
  36702. }
  36703. // Result
  36704. var vertexData = new VertexData();
  36705. var positions32 = new Float32Array(positions);
  36706. var normals32 = new Float32Array(normals);
  36707. var uvs32 = new Float32Array(uvs);
  36708. vertexData.indices = indices;
  36709. vertexData.positions = positions32;
  36710. vertexData.normals = normals32;
  36711. vertexData.uvs = uvs32;
  36712. if (colors) {
  36713. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36714. }
  36715. if (closePath) {
  36716. vertexData._idx = idx;
  36717. }
  36718. return vertexData;
  36719. };
  36720. /**
  36721. * Creates the VertexData for a box
  36722. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36723. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36724. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36725. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36726. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36727. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36728. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36729. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36730. * * 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)
  36731. * * 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)
  36732. * @returns the VertexData of the box
  36733. */
  36734. VertexData.CreateBox = function (options) {
  36735. var normalsSource = [
  36736. new BABYLON.Vector3(0, 0, 1),
  36737. new BABYLON.Vector3(0, 0, -1),
  36738. new BABYLON.Vector3(1, 0, 0),
  36739. new BABYLON.Vector3(-1, 0, 0),
  36740. new BABYLON.Vector3(0, 1, 0),
  36741. new BABYLON.Vector3(0, -1, 0)
  36742. ];
  36743. var indices = [];
  36744. var positions = [];
  36745. var normals = [];
  36746. var uvs = [];
  36747. var width = options.width || options.size || 1;
  36748. var height = options.height || options.size || 1;
  36749. var depth = options.depth || options.size || 1;
  36750. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36751. var faceUV = options.faceUV || new Array(6);
  36752. var faceColors = options.faceColors;
  36753. var colors = [];
  36754. // default face colors and UV if undefined
  36755. for (var f = 0; f < 6; f++) {
  36756. if (faceUV[f] === undefined) {
  36757. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36758. }
  36759. if (faceColors && faceColors[f] === undefined) {
  36760. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36761. }
  36762. }
  36763. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36764. // Create each face in turn.
  36765. for (var index = 0; index < normalsSource.length; index++) {
  36766. var normal = normalsSource[index];
  36767. // Get two vectors perpendicular to the face normal and to each other.
  36768. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36769. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36770. // Six indices (two triangles) per face.
  36771. var verticesLength = positions.length / 3;
  36772. indices.push(verticesLength);
  36773. indices.push(verticesLength + 1);
  36774. indices.push(verticesLength + 2);
  36775. indices.push(verticesLength);
  36776. indices.push(verticesLength + 2);
  36777. indices.push(verticesLength + 3);
  36778. // Four vertices per face.
  36779. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36780. positions.push(vertex.x, vertex.y, vertex.z);
  36781. normals.push(normal.x, normal.y, normal.z);
  36782. uvs.push(faceUV[index].z, faceUV[index].w);
  36783. if (faceColors) {
  36784. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36785. }
  36786. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36787. positions.push(vertex.x, vertex.y, vertex.z);
  36788. normals.push(normal.x, normal.y, normal.z);
  36789. uvs.push(faceUV[index].x, faceUV[index].w);
  36790. if (faceColors) {
  36791. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36792. }
  36793. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36794. positions.push(vertex.x, vertex.y, vertex.z);
  36795. normals.push(normal.x, normal.y, normal.z);
  36796. uvs.push(faceUV[index].x, faceUV[index].y);
  36797. if (faceColors) {
  36798. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36799. }
  36800. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36801. positions.push(vertex.x, vertex.y, vertex.z);
  36802. normals.push(normal.x, normal.y, normal.z);
  36803. uvs.push(faceUV[index].z, faceUV[index].y);
  36804. if (faceColors) {
  36805. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36806. }
  36807. }
  36808. // sides
  36809. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36810. // Result
  36811. var vertexData = new VertexData();
  36812. vertexData.indices = indices;
  36813. vertexData.positions = positions;
  36814. vertexData.normals = normals;
  36815. vertexData.uvs = uvs;
  36816. if (faceColors) {
  36817. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36818. vertexData.colors = totalColors;
  36819. }
  36820. return vertexData;
  36821. };
  36822. /**
  36823. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36824. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36825. * * segments sets the number of horizontal strips optional, default 32
  36826. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36827. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36828. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36829. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36830. * * 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
  36831. * * 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
  36832. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36833. * * 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)
  36834. * * 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)
  36835. * @returns the VertexData of the ellipsoid
  36836. */
  36837. VertexData.CreateSphere = function (options) {
  36838. var segments = options.segments || 32;
  36839. var diameterX = options.diameterX || options.diameter || 1;
  36840. var diameterY = options.diameterY || options.diameter || 1;
  36841. var diameterZ = options.diameterZ || options.diameter || 1;
  36842. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36843. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36844. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36845. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36846. var totalZRotationSteps = 2 + segments;
  36847. var totalYRotationSteps = 2 * totalZRotationSteps;
  36848. var indices = [];
  36849. var positions = [];
  36850. var normals = [];
  36851. var uvs = [];
  36852. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36853. var normalizedZ = zRotationStep / totalZRotationSteps;
  36854. var angleZ = normalizedZ * Math.PI * slice;
  36855. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36856. var normalizedY = yRotationStep / totalYRotationSteps;
  36857. var angleY = normalizedY * Math.PI * 2 * arc;
  36858. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36859. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36860. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36861. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36862. var vertex = complete.multiply(radius);
  36863. var normal = complete.divide(radius).normalize();
  36864. positions.push(vertex.x, vertex.y, vertex.z);
  36865. normals.push(normal.x, normal.y, normal.z);
  36866. uvs.push(normalizedY, normalizedZ);
  36867. }
  36868. if (zRotationStep > 0) {
  36869. var verticesCount = positions.length / 3;
  36870. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36871. indices.push((firstIndex));
  36872. indices.push((firstIndex + 1));
  36873. indices.push(firstIndex + totalYRotationSteps + 1);
  36874. indices.push((firstIndex + totalYRotationSteps + 1));
  36875. indices.push((firstIndex + 1));
  36876. indices.push((firstIndex + totalYRotationSteps + 2));
  36877. }
  36878. }
  36879. }
  36880. // Sides
  36881. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36882. // Result
  36883. var vertexData = new VertexData();
  36884. vertexData.indices = indices;
  36885. vertexData.positions = positions;
  36886. vertexData.normals = normals;
  36887. vertexData.uvs = uvs;
  36888. return vertexData;
  36889. };
  36890. /**
  36891. * Creates the VertexData for a cylinder, cone or prism
  36892. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36893. * * height sets the height (y direction) of the cylinder, optional, default 2
  36894. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36895. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36896. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36897. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36898. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36899. * * 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
  36900. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36901. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36902. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36903. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36904. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36905. * * 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)
  36906. * * 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)
  36907. * @returns the VertexData of the cylinder, cone or prism
  36908. */
  36909. VertexData.CreateCylinder = function (options) {
  36910. var height = options.height || 2;
  36911. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36912. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36913. var tessellation = options.tessellation || 24;
  36914. var subdivisions = options.subdivisions || 1;
  36915. var hasRings = options.hasRings ? true : false;
  36916. var enclose = options.enclose ? true : false;
  36917. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36918. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36919. var faceUV = options.faceUV || new Array(3);
  36920. var faceColors = options.faceColors;
  36921. // default face colors and UV if undefined
  36922. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36923. var ringNb = (hasRings) ? subdivisions : 1;
  36924. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36925. var f;
  36926. for (f = 0; f < surfaceNb; f++) {
  36927. if (faceColors && faceColors[f] === undefined) {
  36928. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36929. }
  36930. }
  36931. for (f = 0; f < surfaceNb; f++) {
  36932. if (faceUV && faceUV[f] === undefined) {
  36933. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36934. }
  36935. }
  36936. var indices = new Array();
  36937. var positions = new Array();
  36938. var normals = new Array();
  36939. var uvs = new Array();
  36940. var colors = new Array();
  36941. var angle_step = Math.PI * 2 * arc / tessellation;
  36942. var angle;
  36943. var h;
  36944. var radius;
  36945. var tan = (diameterBottom - diameterTop) / 2 / height;
  36946. var ringVertex = BABYLON.Vector3.Zero();
  36947. var ringNormal = BABYLON.Vector3.Zero();
  36948. var ringFirstVertex = BABYLON.Vector3.Zero();
  36949. var ringFirstNormal = BABYLON.Vector3.Zero();
  36950. var quadNormal = BABYLON.Vector3.Zero();
  36951. var Y = BABYLON.Axis.Y;
  36952. // positions, normals, uvs
  36953. var i;
  36954. var j;
  36955. var r;
  36956. var ringIdx = 1;
  36957. var s = 1; // surface index
  36958. var cs = 0;
  36959. var v = 0;
  36960. for (i = 0; i <= subdivisions; i++) {
  36961. h = i / subdivisions;
  36962. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36963. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36964. for (r = 0; r < ringIdx; r++) {
  36965. if (hasRings) {
  36966. s += r;
  36967. }
  36968. if (enclose) {
  36969. s += 2 * r;
  36970. }
  36971. for (j = 0; j <= tessellation; j++) {
  36972. angle = j * angle_step;
  36973. // position
  36974. ringVertex.x = Math.cos(-angle) * radius;
  36975. ringVertex.y = -height / 2 + h * height;
  36976. ringVertex.z = Math.sin(-angle) * radius;
  36977. // normal
  36978. if (diameterTop === 0 && i === subdivisions) {
  36979. // if no top cap, reuse former normals
  36980. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36981. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36982. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36983. }
  36984. else {
  36985. ringNormal.x = ringVertex.x;
  36986. ringNormal.z = ringVertex.z;
  36987. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36988. ringNormal.normalize();
  36989. }
  36990. // keep first ring vertex values for enclose
  36991. if (j === 0) {
  36992. ringFirstVertex.copyFrom(ringVertex);
  36993. ringFirstNormal.copyFrom(ringNormal);
  36994. }
  36995. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36996. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36997. if (hasRings) {
  36998. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36999. }
  37000. else {
  37001. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37002. }
  37003. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37004. if (faceColors) {
  37005. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37006. }
  37007. }
  37008. // if enclose, add four vertices and their dedicated normals
  37009. if (arc !== 1 && enclose) {
  37010. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37011. positions.push(0, ringVertex.y, 0);
  37012. positions.push(0, ringVertex.y, 0);
  37013. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37014. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37015. quadNormal.normalize();
  37016. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37017. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37018. quadNormal.normalize();
  37019. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37020. if (hasRings) {
  37021. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37022. }
  37023. else {
  37024. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37025. }
  37026. uvs.push(faceUV[s + 1].x, v);
  37027. uvs.push(faceUV[s + 1].z, v);
  37028. if (hasRings) {
  37029. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37030. }
  37031. else {
  37032. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37033. }
  37034. uvs.push(faceUV[s + 2].x, v);
  37035. uvs.push(faceUV[s + 2].z, v);
  37036. if (faceColors) {
  37037. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37038. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37039. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37040. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37041. }
  37042. }
  37043. if (cs !== s) {
  37044. cs = s;
  37045. }
  37046. }
  37047. }
  37048. // indices
  37049. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37050. var s;
  37051. i = 0;
  37052. for (s = 0; s < subdivisions; s++) {
  37053. var i0 = 0;
  37054. var i1 = 0;
  37055. var i2 = 0;
  37056. var i3 = 0;
  37057. for (j = 0; j < tessellation; j++) {
  37058. i0 = i * (e + 1) + j;
  37059. i1 = (i + 1) * (e + 1) + j;
  37060. i2 = i * (e + 1) + (j + 1);
  37061. i3 = (i + 1) * (e + 1) + (j + 1);
  37062. indices.push(i0, i1, i2);
  37063. indices.push(i3, i2, i1);
  37064. }
  37065. if (arc !== 1 && enclose) { // if enclose, add two quads
  37066. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37067. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37068. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37069. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37070. }
  37071. i = (hasRings) ? (i + 2) : (i + 1);
  37072. }
  37073. // Caps
  37074. var createCylinderCap = function (isTop) {
  37075. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37076. if (radius === 0) {
  37077. return;
  37078. }
  37079. // Cap positions, normals & uvs
  37080. var angle;
  37081. var circleVector;
  37082. var i;
  37083. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37084. var c = null;
  37085. if (faceColors) {
  37086. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37087. }
  37088. // cap center
  37089. var vbase = positions.length / 3;
  37090. var offset = isTop ? height / 2 : -height / 2;
  37091. var center = new BABYLON.Vector3(0, offset, 0);
  37092. positions.push(center.x, center.y, center.z);
  37093. normals.push(0, isTop ? 1 : -1, 0);
  37094. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37095. if (c) {
  37096. colors.push(c.r, c.g, c.b, c.a);
  37097. }
  37098. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37099. for (i = 0; i <= tessellation; i++) {
  37100. angle = Math.PI * 2 * i * arc / tessellation;
  37101. var cos = Math.cos(-angle);
  37102. var sin = Math.sin(-angle);
  37103. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37104. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37105. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37106. normals.push(0, isTop ? 1 : -1, 0);
  37107. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37108. if (c) {
  37109. colors.push(c.r, c.g, c.b, c.a);
  37110. }
  37111. }
  37112. // Cap indices
  37113. for (i = 0; i < tessellation; i++) {
  37114. if (!isTop) {
  37115. indices.push(vbase);
  37116. indices.push(vbase + (i + 1));
  37117. indices.push(vbase + (i + 2));
  37118. }
  37119. else {
  37120. indices.push(vbase);
  37121. indices.push(vbase + (i + 2));
  37122. indices.push(vbase + (i + 1));
  37123. }
  37124. }
  37125. };
  37126. // add caps to geometry
  37127. createCylinderCap(false);
  37128. createCylinderCap(true);
  37129. // Sides
  37130. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37131. var vertexData = new VertexData();
  37132. vertexData.indices = indices;
  37133. vertexData.positions = positions;
  37134. vertexData.normals = normals;
  37135. vertexData.uvs = uvs;
  37136. if (faceColors) {
  37137. vertexData.colors = colors;
  37138. }
  37139. return vertexData;
  37140. };
  37141. /**
  37142. * Creates the VertexData for a torus
  37143. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37144. * * diameter the diameter of the torus, optional default 1
  37145. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37146. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37147. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37148. * * 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)
  37149. * * 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)
  37150. * @returns the VertexData of the torus
  37151. */
  37152. VertexData.CreateTorus = function (options) {
  37153. var indices = [];
  37154. var positions = [];
  37155. var normals = [];
  37156. var uvs = [];
  37157. var diameter = options.diameter || 1;
  37158. var thickness = options.thickness || 0.5;
  37159. var tessellation = options.tessellation || 16;
  37160. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37161. var stride = tessellation + 1;
  37162. for (var i = 0; i <= tessellation; i++) {
  37163. var u = i / tessellation;
  37164. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37165. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37166. for (var j = 0; j <= tessellation; j++) {
  37167. var v = 1 - j / tessellation;
  37168. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37169. var dx = Math.cos(innerAngle);
  37170. var dy = Math.sin(innerAngle);
  37171. // Create a vertex.
  37172. var normal = new BABYLON.Vector3(dx, dy, 0);
  37173. var position = normal.scale(thickness / 2);
  37174. var textureCoordinate = new BABYLON.Vector2(u, v);
  37175. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37176. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37177. positions.push(position.x, position.y, position.z);
  37178. normals.push(normal.x, normal.y, normal.z);
  37179. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37180. // And create indices for two triangles.
  37181. var nextI = (i + 1) % stride;
  37182. var nextJ = (j + 1) % stride;
  37183. indices.push(i * stride + j);
  37184. indices.push(i * stride + nextJ);
  37185. indices.push(nextI * stride + j);
  37186. indices.push(i * stride + nextJ);
  37187. indices.push(nextI * stride + nextJ);
  37188. indices.push(nextI * stride + j);
  37189. }
  37190. }
  37191. // Sides
  37192. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37193. // Result
  37194. var vertexData = new VertexData();
  37195. vertexData.indices = indices;
  37196. vertexData.positions = positions;
  37197. vertexData.normals = normals;
  37198. vertexData.uvs = uvs;
  37199. return vertexData;
  37200. };
  37201. /**
  37202. * Creates the VertexData of the LineSystem
  37203. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37204. * - lines an array of lines, each line being an array of successive Vector3
  37205. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37206. * @returns the VertexData of the LineSystem
  37207. */
  37208. VertexData.CreateLineSystem = function (options) {
  37209. var indices = [];
  37210. var positions = [];
  37211. var lines = options.lines;
  37212. var colors = options.colors;
  37213. var vertexColors = [];
  37214. var idx = 0;
  37215. for (var l = 0; l < lines.length; l++) {
  37216. var points = lines[l];
  37217. for (var index = 0; index < points.length; index++) {
  37218. positions.push(points[index].x, points[index].y, points[index].z);
  37219. if (colors) {
  37220. var color = colors[l];
  37221. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37222. }
  37223. if (index > 0) {
  37224. indices.push(idx - 1);
  37225. indices.push(idx);
  37226. }
  37227. idx++;
  37228. }
  37229. }
  37230. var vertexData = new VertexData();
  37231. vertexData.indices = indices;
  37232. vertexData.positions = positions;
  37233. if (colors) {
  37234. vertexData.colors = vertexColors;
  37235. }
  37236. return vertexData;
  37237. };
  37238. /**
  37239. * Create the VertexData for a DashedLines
  37240. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37241. * - points an array successive Vector3
  37242. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37243. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37244. * - dashNb the intended total number of dashes, optional, default 200
  37245. * @returns the VertexData for the DashedLines
  37246. */
  37247. VertexData.CreateDashedLines = function (options) {
  37248. var dashSize = options.dashSize || 3;
  37249. var gapSize = options.gapSize || 1;
  37250. var dashNb = options.dashNb || 200;
  37251. var points = options.points;
  37252. var positions = new Array();
  37253. var indices = new Array();
  37254. var curvect = BABYLON.Vector3.Zero();
  37255. var lg = 0;
  37256. var nb = 0;
  37257. var shft = 0;
  37258. var dashshft = 0;
  37259. var curshft = 0;
  37260. var idx = 0;
  37261. var i = 0;
  37262. for (i = 0; i < points.length - 1; i++) {
  37263. points[i + 1].subtractToRef(points[i], curvect);
  37264. lg += curvect.length();
  37265. }
  37266. shft = lg / dashNb;
  37267. dashshft = dashSize * shft / (dashSize + gapSize);
  37268. for (i = 0; i < points.length - 1; i++) {
  37269. points[i + 1].subtractToRef(points[i], curvect);
  37270. nb = Math.floor(curvect.length() / shft);
  37271. curvect.normalize();
  37272. for (var j = 0; j < nb; j++) {
  37273. curshft = shft * j;
  37274. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37275. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37276. indices.push(idx, idx + 1);
  37277. idx += 2;
  37278. }
  37279. }
  37280. // Result
  37281. var vertexData = new VertexData();
  37282. vertexData.positions = positions;
  37283. vertexData.indices = indices;
  37284. return vertexData;
  37285. };
  37286. /**
  37287. * Creates the VertexData for a Ground
  37288. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37289. * - width the width (x direction) of the ground, optional, default 1
  37290. * - height the height (z direction) of the ground, optional, default 1
  37291. * - subdivisions the number of subdivisions per side, optional, default 1
  37292. * @returns the VertexData of the Ground
  37293. */
  37294. VertexData.CreateGround = function (options) {
  37295. var indices = [];
  37296. var positions = [];
  37297. var normals = [];
  37298. var uvs = [];
  37299. var row, col;
  37300. var width = options.width || 1;
  37301. var height = options.height || 1;
  37302. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37303. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37304. for (row = 0; row <= subdivisionsY; row++) {
  37305. for (col = 0; col <= subdivisionsX; col++) {
  37306. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37307. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37308. positions.push(position.x, position.y, position.z);
  37309. normals.push(normal.x, normal.y, normal.z);
  37310. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37311. }
  37312. }
  37313. for (row = 0; row < subdivisionsY; row++) {
  37314. for (col = 0; col < subdivisionsX; col++) {
  37315. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37316. indices.push(col + 1 + row * (subdivisionsX + 1));
  37317. indices.push(col + row * (subdivisionsX + 1));
  37318. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37319. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37320. indices.push(col + row * (subdivisionsX + 1));
  37321. }
  37322. }
  37323. // Result
  37324. var vertexData = new VertexData();
  37325. vertexData.indices = indices;
  37326. vertexData.positions = positions;
  37327. vertexData.normals = normals;
  37328. vertexData.uvs = uvs;
  37329. return vertexData;
  37330. };
  37331. /**
  37332. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37333. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37334. * * xmin the ground minimum X coordinate, optional, default -1
  37335. * * zmin the ground minimum Z coordinate, optional, default -1
  37336. * * xmax the ground maximum X coordinate, optional, default 1
  37337. * * zmax the ground maximum Z coordinate, optional, default 1
  37338. * * 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}
  37339. * * 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}
  37340. * @returns the VertexData of the TiledGround
  37341. */
  37342. VertexData.CreateTiledGround = function (options) {
  37343. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37344. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37345. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37346. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37347. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37348. var precision = options.precision || { w: 1, h: 1 };
  37349. var indices = new Array();
  37350. var positions = new Array();
  37351. var normals = new Array();
  37352. var uvs = new Array();
  37353. var row, col, tileRow, tileCol;
  37354. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37355. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37356. precision.w = (precision.w < 1) ? 1 : precision.w;
  37357. precision.h = (precision.h < 1) ? 1 : precision.h;
  37358. var tileSize = {
  37359. 'w': (xmax - xmin) / subdivisions.w,
  37360. 'h': (zmax - zmin) / subdivisions.h
  37361. };
  37362. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37363. // Indices
  37364. var base = positions.length / 3;
  37365. var rowLength = precision.w + 1;
  37366. for (row = 0; row < precision.h; row++) {
  37367. for (col = 0; col < precision.w; col++) {
  37368. var square = [
  37369. base + col + row * rowLength,
  37370. base + (col + 1) + row * rowLength,
  37371. base + (col + 1) + (row + 1) * rowLength,
  37372. base + col + (row + 1) * rowLength
  37373. ];
  37374. indices.push(square[1]);
  37375. indices.push(square[2]);
  37376. indices.push(square[3]);
  37377. indices.push(square[0]);
  37378. indices.push(square[1]);
  37379. indices.push(square[3]);
  37380. }
  37381. }
  37382. // Position, normals and uvs
  37383. var position = BABYLON.Vector3.Zero();
  37384. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37385. for (row = 0; row <= precision.h; row++) {
  37386. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37387. for (col = 0; col <= precision.w; col++) {
  37388. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37389. position.y = 0;
  37390. positions.push(position.x, position.y, position.z);
  37391. normals.push(normal.x, normal.y, normal.z);
  37392. uvs.push(col / precision.w, row / precision.h);
  37393. }
  37394. }
  37395. }
  37396. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37397. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37398. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37399. }
  37400. }
  37401. // Result
  37402. var vertexData = new VertexData();
  37403. vertexData.indices = indices;
  37404. vertexData.positions = positions;
  37405. vertexData.normals = normals;
  37406. vertexData.uvs = uvs;
  37407. return vertexData;
  37408. };
  37409. /**
  37410. * Creates the VertexData of the Ground designed from a heightmap
  37411. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37412. * * width the width (x direction) of the ground
  37413. * * height the height (z direction) of the ground
  37414. * * subdivisions the number of subdivisions per side
  37415. * * minHeight the minimum altitude on the ground, optional, default 0
  37416. * * maxHeight the maximum altitude on the ground, optional default 1
  37417. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37418. * * buffer the array holding the image color data
  37419. * * bufferWidth the width of image
  37420. * * bufferHeight the height of image
  37421. * @returns the VertexData of the Ground designed from a heightmap
  37422. */
  37423. VertexData.CreateGroundFromHeightMap = function (options) {
  37424. var indices = [];
  37425. var positions = [];
  37426. var normals = [];
  37427. var uvs = [];
  37428. var row, col;
  37429. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37430. // Vertices
  37431. for (row = 0; row <= options.subdivisions; row++) {
  37432. for (col = 0; col <= options.subdivisions; col++) {
  37433. 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));
  37434. // Compute height
  37435. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37436. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37437. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37438. var r = options.buffer[pos] / 255.0;
  37439. var g = options.buffer[pos + 1] / 255.0;
  37440. var b = options.buffer[pos + 2] / 255.0;
  37441. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37442. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37443. // Add vertex
  37444. positions.push(position.x, position.y, position.z);
  37445. normals.push(0, 0, 0);
  37446. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37447. }
  37448. }
  37449. // Indices
  37450. for (row = 0; row < options.subdivisions; row++) {
  37451. for (col = 0; col < options.subdivisions; col++) {
  37452. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37453. indices.push(col + 1 + row * (options.subdivisions + 1));
  37454. indices.push(col + row * (options.subdivisions + 1));
  37455. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37456. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37457. indices.push(col + row * (options.subdivisions + 1));
  37458. }
  37459. }
  37460. // Normals
  37461. VertexData.ComputeNormals(positions, indices, normals);
  37462. // Result
  37463. var vertexData = new VertexData();
  37464. vertexData.indices = indices;
  37465. vertexData.positions = positions;
  37466. vertexData.normals = normals;
  37467. vertexData.uvs = uvs;
  37468. return vertexData;
  37469. };
  37470. /**
  37471. * Creates the VertexData for a Plane
  37472. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37473. * * size sets the width and height of the plane to the value of size, optional default 1
  37474. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37475. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37476. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37477. * * 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)
  37478. * * 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)
  37479. * @returns the VertexData of the box
  37480. */
  37481. VertexData.CreatePlane = function (options) {
  37482. var indices = [];
  37483. var positions = [];
  37484. var normals = [];
  37485. var uvs = [];
  37486. var width = options.width || options.size || 1;
  37487. var height = options.height || options.size || 1;
  37488. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37489. // Vertices
  37490. var halfWidth = width / 2.0;
  37491. var halfHeight = height / 2.0;
  37492. positions.push(-halfWidth, -halfHeight, 0);
  37493. normals.push(0, 0, -1.0);
  37494. uvs.push(0.0, 0.0);
  37495. positions.push(halfWidth, -halfHeight, 0);
  37496. normals.push(0, 0, -1.0);
  37497. uvs.push(1.0, 0.0);
  37498. positions.push(halfWidth, halfHeight, 0);
  37499. normals.push(0, 0, -1.0);
  37500. uvs.push(1.0, 1.0);
  37501. positions.push(-halfWidth, halfHeight, 0);
  37502. normals.push(0, 0, -1.0);
  37503. uvs.push(0.0, 1.0);
  37504. // Indices
  37505. indices.push(0);
  37506. indices.push(1);
  37507. indices.push(2);
  37508. indices.push(0);
  37509. indices.push(2);
  37510. indices.push(3);
  37511. // Sides
  37512. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37513. // Result
  37514. var vertexData = new VertexData();
  37515. vertexData.indices = indices;
  37516. vertexData.positions = positions;
  37517. vertexData.normals = normals;
  37518. vertexData.uvs = uvs;
  37519. return vertexData;
  37520. };
  37521. /**
  37522. * Creates the VertexData of the Disc or regular Polygon
  37523. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37524. * * radius the radius of the disc, optional default 0.5
  37525. * * tessellation the number of polygon sides, optional, default 64
  37526. * * 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
  37527. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37528. * * 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)
  37529. * * 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)
  37530. * @returns the VertexData of the box
  37531. */
  37532. VertexData.CreateDisc = function (options) {
  37533. var positions = new Array();
  37534. var indices = new Array();
  37535. var normals = new Array();
  37536. var uvs = new Array();
  37537. var radius = options.radius || 0.5;
  37538. var tessellation = options.tessellation || 64;
  37539. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37540. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37541. // positions and uvs
  37542. positions.push(0, 0, 0); // disc center first
  37543. uvs.push(0.5, 0.5);
  37544. var theta = Math.PI * 2 * arc;
  37545. var step = theta / tessellation;
  37546. for (var a = 0; a < theta; a += step) {
  37547. var x = Math.cos(a);
  37548. var y = Math.sin(a);
  37549. var u = (x + 1) / 2;
  37550. var v = (1 - y) / 2;
  37551. positions.push(radius * x, radius * y, 0);
  37552. uvs.push(u, v);
  37553. }
  37554. if (arc === 1) {
  37555. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37556. uvs.push(uvs[2], uvs[3]);
  37557. }
  37558. //indices
  37559. var vertexNb = positions.length / 3;
  37560. for (var i = 1; i < vertexNb - 1; i++) {
  37561. indices.push(i + 1, 0, i);
  37562. }
  37563. // result
  37564. VertexData.ComputeNormals(positions, indices, normals);
  37565. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37566. var vertexData = new VertexData();
  37567. vertexData.indices = indices;
  37568. vertexData.positions = positions;
  37569. vertexData.normals = normals;
  37570. vertexData.uvs = uvs;
  37571. return vertexData;
  37572. };
  37573. /**
  37574. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37575. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37576. * @param polygon a mesh built from polygonTriangulation.build()
  37577. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37578. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37579. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37580. * @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)
  37581. * @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)
  37582. * @returns the VertexData of the Polygon
  37583. */
  37584. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37585. var faceUV = fUV || new Array(3);
  37586. var faceColors = fColors;
  37587. var colors = [];
  37588. // default face colors and UV if undefined
  37589. for (var f = 0; f < 3; f++) {
  37590. if (faceUV[f] === undefined) {
  37591. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37592. }
  37593. if (faceColors && faceColors[f] === undefined) {
  37594. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37595. }
  37596. }
  37597. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37598. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37599. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37600. var indices = polygon.getIndices();
  37601. // set face colours and textures
  37602. var idx = 0;
  37603. var face = 0;
  37604. for (var index = 0; index < normals.length; index += 3) {
  37605. //Edge Face no. 1
  37606. if (Math.abs(normals[index + 1]) < 0.001) {
  37607. face = 1;
  37608. }
  37609. //Top Face no. 0
  37610. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37611. face = 0;
  37612. }
  37613. //Bottom Face no. 2
  37614. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37615. face = 2;
  37616. }
  37617. idx = index / 3;
  37618. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37619. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37620. if (faceColors) {
  37621. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37622. }
  37623. }
  37624. // sides
  37625. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37626. // Result
  37627. var vertexData = new VertexData();
  37628. vertexData.indices = indices;
  37629. vertexData.positions = positions;
  37630. vertexData.normals = normals;
  37631. vertexData.uvs = uvs;
  37632. if (faceColors) {
  37633. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37634. vertexData.colors = totalColors;
  37635. }
  37636. return vertexData;
  37637. };
  37638. /**
  37639. * Creates the VertexData of the IcoSphere
  37640. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37641. * * radius the radius of the IcoSphere, optional default 1
  37642. * * radiusX allows stretching in the x direction, optional, default radius
  37643. * * radiusY allows stretching in the y direction, optional, default radius
  37644. * * radiusZ allows stretching in the z direction, optional, default radius
  37645. * * flat when true creates a flat shaded mesh, optional, default true
  37646. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37647. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37648. * * 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)
  37649. * * 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)
  37650. * @returns the VertexData of the IcoSphere
  37651. */
  37652. VertexData.CreateIcoSphere = function (options) {
  37653. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37654. var radius = options.radius || 1;
  37655. var flat = (options.flat === undefined) ? true : options.flat;
  37656. var subdivisions = options.subdivisions || 4;
  37657. var radiusX = options.radiusX || radius;
  37658. var radiusY = options.radiusY || radius;
  37659. var radiusZ = options.radiusZ || radius;
  37660. var t = (1 + Math.sqrt(5)) / 2;
  37661. // 12 vertex x,y,z
  37662. var ico_vertices = [
  37663. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37664. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37665. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37666. ];
  37667. // index of 3 vertex makes a face of icopshere
  37668. var ico_indices = [
  37669. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37670. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37671. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37672. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37673. ];
  37674. // vertex for uv have aliased position, not for UV
  37675. var vertices_unalias_id = [
  37676. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37677. // vertex alias
  37678. 0,
  37679. 2,
  37680. 3,
  37681. 3,
  37682. 3,
  37683. 4,
  37684. 7,
  37685. 8,
  37686. 9,
  37687. 9,
  37688. 10,
  37689. 11 // 23: B + 12
  37690. ];
  37691. // uv as integer step (not pixels !)
  37692. var ico_vertexuv = [
  37693. 5, 1, 3, 1, 6, 4, 0, 0,
  37694. 5, 3, 4, 2, 2, 2, 4, 0,
  37695. 2, 0, 1, 1, 6, 0, 6, 2,
  37696. // vertex alias (for same vertex on different faces)
  37697. 0, 4,
  37698. 3, 3,
  37699. 4, 4,
  37700. 3, 1,
  37701. 4, 2,
  37702. 4, 4,
  37703. 0, 2,
  37704. 1, 1,
  37705. 2, 2,
  37706. 3, 3,
  37707. 1, 3,
  37708. 2, 4 // 23: B + 12
  37709. ];
  37710. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37711. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37712. // First island of uv mapping
  37713. // v = 4h 3+ 2
  37714. // v = 3h 9+ 4
  37715. // v = 2h 9+ 5 B
  37716. // v = 1h 9 1 0
  37717. // v = 0h 3 8 7 A
  37718. // u = 0 1 2 3 4 5 6 *a
  37719. // Second island of uv mapping
  37720. // v = 4h 0+ B+ 4+
  37721. // v = 3h A+ 2+
  37722. // v = 2h 7+ 6 3+
  37723. // v = 1h 8+ 3+
  37724. // v = 0h
  37725. // u = 0 1 2 3 4 5 6 *a
  37726. // Face layout on texture UV mapping
  37727. // ============
  37728. // \ 4 /\ 16 / ======
  37729. // \ / \ / /\ 11 /
  37730. // \/ 7 \/ / \ /
  37731. // ======= / 10 \/
  37732. // /\ 17 /\ =======
  37733. // / \ / \ \ 15 /\
  37734. // / 8 \/ 12 \ \ / \
  37735. // ============ \/ 6 \
  37736. // \ 18 /\ ============
  37737. // \ / \ \ 5 /\ 0 /
  37738. // \/ 13 \ \ / \ /
  37739. // ======= \/ 1 \/
  37740. // =============
  37741. // /\ 19 /\ 2 /\
  37742. // / \ / \ / \
  37743. // / 14 \/ 9 \/ 3 \
  37744. // ===================
  37745. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37746. var ustep = 138 / 1024;
  37747. var vstep = 239 / 1024;
  37748. var uoffset = 60 / 1024;
  37749. var voffset = 26 / 1024;
  37750. // Second island should have margin, not to touch the first island
  37751. // avoid any borderline artefact in pixel rounding
  37752. var island_u_offset = -40 / 1024;
  37753. var island_v_offset = +20 / 1024;
  37754. // face is either island 0 or 1 :
  37755. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37756. var island = [
  37757. 0, 0, 0, 0, 1,
  37758. 0, 0, 1, 1, 0,
  37759. 0, 0, 1, 1, 0,
  37760. 0, 1, 1, 1, 0 // 15 - 19
  37761. ];
  37762. var indices = new Array();
  37763. var positions = new Array();
  37764. var normals = new Array();
  37765. var uvs = new Array();
  37766. var current_indice = 0;
  37767. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37768. var face_vertex_pos = new Array(3);
  37769. var face_vertex_uv = new Array(3);
  37770. var v012;
  37771. for (v012 = 0; v012 < 3; v012++) {
  37772. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37773. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37774. }
  37775. // create all with normals
  37776. for (var face = 0; face < 20; face++) {
  37777. // 3 vertex per face
  37778. for (v012 = 0; v012 < 3; v012++) {
  37779. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37780. var v_id = ico_indices[3 * face + v012];
  37781. // vertex have 3D position (x,y,z)
  37782. 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]);
  37783. // Normalize to get normal, then scale to radius
  37784. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37785. // uv Coordinates from vertex ID
  37786. 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);
  37787. }
  37788. // Subdivide the face (interpolate pos, norm, uv)
  37789. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37790. // - norm is linear interpolation of vertex corner normal
  37791. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37792. // - uv is linear interpolation
  37793. //
  37794. // Topology is as below for sub-divide by 2
  37795. // vertex shown as v0,v1,v2
  37796. // interp index is i1 to progress in range [v0,v1[
  37797. // interp index is i2 to progress in range [v0,v2[
  37798. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37799. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37800. //
  37801. //
  37802. // i2 v2
  37803. // ^ ^
  37804. // / / \
  37805. // / / \
  37806. // / / \
  37807. // / / (0,1) \
  37808. // / #---------\
  37809. // / / \ (0,0)'/ \
  37810. // / / \ / \
  37811. // / / \ / \
  37812. // / / (0,0) \ / (1,0) \
  37813. // / #---------#---------\
  37814. // v0 v1
  37815. //
  37816. // --------------------> i1
  37817. //
  37818. // interp of (i1,i2):
  37819. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37820. // along i1 : lerp(x0,x1, i1/(S-i2))
  37821. //
  37822. // centroid of triangle is needed to get help normal computation
  37823. // (c1,c2) are used for centroid location
  37824. var interp_vertex = function (i1, i2, c1, c2) {
  37825. // vertex is interpolated from
  37826. // - face_vertex_pos[0..2]
  37827. // - face_vertex_uv[0..2]
  37828. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37829. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37830. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37831. pos_interp.normalize();
  37832. var vertex_normal;
  37833. if (flat) {
  37834. // in flat mode, recalculate normal as face centroid normal
  37835. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37836. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37837. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37838. }
  37839. else {
  37840. // in smooth mode, recalculate normal from each single vertex position
  37841. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37842. }
  37843. // Vertex normal need correction due to X,Y,Z radius scaling
  37844. vertex_normal.x /= radiusX;
  37845. vertex_normal.y /= radiusY;
  37846. vertex_normal.z /= radiusZ;
  37847. vertex_normal.normalize();
  37848. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37849. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37850. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37851. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37852. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37853. uvs.push(uv_interp.x, uv_interp.y);
  37854. // push each vertex has member of a face
  37855. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37856. indices.push(current_indice);
  37857. current_indice++;
  37858. };
  37859. for (var i2 = 0; i2 < subdivisions; i2++) {
  37860. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37861. // face : (i1,i2) for /\ :
  37862. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37863. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37864. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37865. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37866. if (i1 + i2 + 1 < subdivisions) {
  37867. // face : (i1,i2)' for \/ :
  37868. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37869. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37870. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37871. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37872. }
  37873. }
  37874. }
  37875. }
  37876. // Sides
  37877. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37878. // Result
  37879. var vertexData = new VertexData();
  37880. vertexData.indices = indices;
  37881. vertexData.positions = positions;
  37882. vertexData.normals = normals;
  37883. vertexData.uvs = uvs;
  37884. return vertexData;
  37885. };
  37886. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37887. /**
  37888. * Creates the VertexData for a Polyhedron
  37889. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37890. * * type provided types are:
  37891. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37892. * * 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)
  37893. * * size the size of the IcoSphere, optional default 1
  37894. * * sizeX allows stretching in the x direction, optional, default size
  37895. * * sizeY allows stretching in the y direction, optional, default size
  37896. * * sizeZ allows stretching in the z direction, optional, default size
  37897. * * 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
  37898. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37899. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37900. * * flat when true creates a flat shaded mesh, optional, default true
  37901. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37902. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37903. * * 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)
  37904. * * 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)
  37905. * @returns the VertexData of the Polyhedron
  37906. */
  37907. VertexData.CreatePolyhedron = function (options) {
  37908. // provided polyhedron types :
  37909. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37910. // 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)
  37911. var polyhedra = [];
  37912. 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]] };
  37913. 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]] };
  37914. polyhedra[2] = {
  37915. 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]],
  37916. 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]]
  37917. };
  37918. polyhedra[3] = {
  37919. 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]],
  37920. 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]]
  37921. };
  37922. polyhedra[4] = {
  37923. 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]],
  37924. 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]]
  37925. };
  37926. 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]] };
  37927. 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]] };
  37928. 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]] };
  37929. 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]] };
  37930. 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]] };
  37931. 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]] };
  37932. 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]] };
  37933. 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]] };
  37934. 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]] };
  37935. polyhedra[14] = {
  37936. 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]],
  37937. 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]]
  37938. };
  37939. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37940. var size = options.size;
  37941. var sizeX = options.sizeX || size || 1;
  37942. var sizeY = options.sizeY || size || 1;
  37943. var sizeZ = options.sizeZ || size || 1;
  37944. var data = options.custom || polyhedra[type];
  37945. var nbfaces = data.face.length;
  37946. var faceUV = options.faceUV || new Array(nbfaces);
  37947. var faceColors = options.faceColors;
  37948. var flat = (options.flat === undefined) ? true : options.flat;
  37949. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37950. var positions = new Array();
  37951. var indices = new Array();
  37952. var normals = new Array();
  37953. var uvs = new Array();
  37954. var colors = new Array();
  37955. var index = 0;
  37956. var faceIdx = 0; // face cursor in the array "indexes"
  37957. var indexes = new Array();
  37958. var i = 0;
  37959. var f = 0;
  37960. var u, v, ang, x, y, tmp;
  37961. // default face colors and UV if undefined
  37962. if (flat) {
  37963. for (f = 0; f < nbfaces; f++) {
  37964. if (faceColors && faceColors[f] === undefined) {
  37965. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37966. }
  37967. if (faceUV && faceUV[f] === undefined) {
  37968. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37969. }
  37970. }
  37971. }
  37972. if (!flat) {
  37973. for (i = 0; i < data.vertex.length; i++) {
  37974. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37975. uvs.push(0, 0);
  37976. }
  37977. for (f = 0; f < nbfaces; f++) {
  37978. for (i = 0; i < data.face[f].length - 2; i++) {
  37979. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37980. }
  37981. }
  37982. }
  37983. else {
  37984. for (f = 0; f < nbfaces; f++) {
  37985. var fl = data.face[f].length; // number of vertices of the current face
  37986. ang = 2 * Math.PI / fl;
  37987. x = 0.5 * Math.tan(ang / 2);
  37988. y = 0.5;
  37989. // positions, uvs, colors
  37990. for (i = 0; i < fl; i++) {
  37991. // positions
  37992. 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);
  37993. indexes.push(index);
  37994. index++;
  37995. // uvs
  37996. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37997. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37998. uvs.push(u, v);
  37999. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38000. y = x * Math.sin(ang) + y * Math.cos(ang);
  38001. x = tmp;
  38002. // colors
  38003. if (faceColors) {
  38004. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38005. }
  38006. }
  38007. // indices from indexes
  38008. for (i = 0; i < fl - 2; i++) {
  38009. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38010. }
  38011. faceIdx += fl;
  38012. }
  38013. }
  38014. VertexData.ComputeNormals(positions, indices, normals);
  38015. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38016. var vertexData = new VertexData();
  38017. vertexData.positions = positions;
  38018. vertexData.indices = indices;
  38019. vertexData.normals = normals;
  38020. vertexData.uvs = uvs;
  38021. if (faceColors && flat) {
  38022. vertexData.colors = colors;
  38023. }
  38024. return vertexData;
  38025. };
  38026. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38027. /**
  38028. * Creates the VertexData for a TorusKnot
  38029. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38030. * * radius the radius of the torus knot, optional, default 2
  38031. * * tube the thickness of the tube, optional, default 0.5
  38032. * * radialSegments the number of sides on each tube segments, optional, default 32
  38033. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38034. * * p the number of windings around the z axis, optional, default 2
  38035. * * q the number of windings around the x axis, optional, default 3
  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 Torus Knot
  38040. */
  38041. VertexData.CreateTorusKnot = function (options) {
  38042. var indices = new Array();
  38043. var positions = new Array();
  38044. var normals = new Array();
  38045. var uvs = new Array();
  38046. var radius = options.radius || 2;
  38047. var tube = options.tube || 0.5;
  38048. var radialSegments = options.radialSegments || 32;
  38049. var tubularSegments = options.tubularSegments || 32;
  38050. var p = options.p || 2;
  38051. var q = options.q || 3;
  38052. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38053. // Helper
  38054. var getPos = function (angle) {
  38055. var cu = Math.cos(angle);
  38056. var su = Math.sin(angle);
  38057. var quOverP = q / p * angle;
  38058. var cs = Math.cos(quOverP);
  38059. var tx = radius * (2 + cs) * 0.5 * cu;
  38060. var ty = radius * (2 + cs) * su * 0.5;
  38061. var tz = radius * Math.sin(quOverP) * 0.5;
  38062. return new BABYLON.Vector3(tx, ty, tz);
  38063. };
  38064. // Vertices
  38065. var i;
  38066. var j;
  38067. for (i = 0; i <= radialSegments; i++) {
  38068. var modI = i % radialSegments;
  38069. var u = modI / radialSegments * 2 * p * Math.PI;
  38070. var p1 = getPos(u);
  38071. var p2 = getPos(u + 0.01);
  38072. var tang = p2.subtract(p1);
  38073. var n = p2.add(p1);
  38074. var bitan = BABYLON.Vector3.Cross(tang, n);
  38075. n = BABYLON.Vector3.Cross(bitan, tang);
  38076. bitan.normalize();
  38077. n.normalize();
  38078. for (j = 0; j < tubularSegments; j++) {
  38079. var modJ = j % tubularSegments;
  38080. var v = modJ / tubularSegments * 2 * Math.PI;
  38081. var cx = -tube * Math.cos(v);
  38082. var cy = tube * Math.sin(v);
  38083. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38084. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38085. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38086. uvs.push(i / radialSegments);
  38087. uvs.push(j / tubularSegments);
  38088. }
  38089. }
  38090. for (i = 0; i < radialSegments; i++) {
  38091. for (j = 0; j < tubularSegments; j++) {
  38092. var jNext = (j + 1) % tubularSegments;
  38093. var a = i * tubularSegments + j;
  38094. var b = (i + 1) * tubularSegments + j;
  38095. var c = (i + 1) * tubularSegments + jNext;
  38096. var d = i * tubularSegments + jNext;
  38097. indices.push(d);
  38098. indices.push(b);
  38099. indices.push(a);
  38100. indices.push(d);
  38101. indices.push(c);
  38102. indices.push(b);
  38103. }
  38104. }
  38105. // Normals
  38106. VertexData.ComputeNormals(positions, indices, normals);
  38107. // Sides
  38108. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38109. // Result
  38110. var vertexData = new VertexData();
  38111. vertexData.indices = indices;
  38112. vertexData.positions = positions;
  38113. vertexData.normals = normals;
  38114. vertexData.uvs = uvs;
  38115. return vertexData;
  38116. };
  38117. // Tools
  38118. /**
  38119. * Compute normals for given positions and indices
  38120. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38121. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38122. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38123. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38124. * * facetNormals : optional array of facet normals (vector3)
  38125. * * facetPositions : optional array of facet positions (vector3)
  38126. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38127. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38128. * * bInfo : optional bounding info, required for facetPartitioning computation
  38129. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38130. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38131. * * useRightHandedSystem: optional boolean to for right handed system computation
  38132. * * depthSort : optional boolean to enable the facet depth sort computation
  38133. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38134. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38135. */
  38136. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38137. // temporary scalar variables
  38138. var index = 0; // facet index
  38139. var p1p2x = 0.0; // p1p2 vector x coordinate
  38140. var p1p2y = 0.0; // p1p2 vector y coordinate
  38141. var p1p2z = 0.0; // p1p2 vector z coordinate
  38142. var p3p2x = 0.0; // p3p2 vector x coordinate
  38143. var p3p2y = 0.0; // p3p2 vector y coordinate
  38144. var p3p2z = 0.0; // p3p2 vector z coordinate
  38145. var faceNormalx = 0.0; // facet normal x coordinate
  38146. var faceNormaly = 0.0; // facet normal y coordinate
  38147. var faceNormalz = 0.0; // facet normal z coordinate
  38148. var length = 0.0; // facet normal length before normalization
  38149. var v1x = 0; // vector1 x index in the positions array
  38150. var v1y = 0; // vector1 y index in the positions array
  38151. var v1z = 0; // vector1 z index in the positions array
  38152. var v2x = 0; // vector2 x index in the positions array
  38153. var v2y = 0; // vector2 y index in the positions array
  38154. var v2z = 0; // vector2 z index in the positions array
  38155. var v3x = 0; // vector3 x index in the positions array
  38156. var v3y = 0; // vector3 y index in the positions array
  38157. var v3z = 0; // vector3 z index in the positions array
  38158. var computeFacetNormals = false;
  38159. var computeFacetPositions = false;
  38160. var computeFacetPartitioning = false;
  38161. var computeDepthSort = false;
  38162. var faceNormalSign = 1;
  38163. var ratio = 0;
  38164. var distanceTo = null;
  38165. if (options) {
  38166. computeFacetNormals = (options.facetNormals) ? true : false;
  38167. computeFacetPositions = (options.facetPositions) ? true : false;
  38168. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38169. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38170. ratio = options.ratio || 0;
  38171. computeDepthSort = (options.depthSort) ? true : false;
  38172. distanceTo = (options.distanceTo);
  38173. if (computeDepthSort) {
  38174. if (distanceTo === undefined) {
  38175. distanceTo = BABYLON.Vector3.Zero();
  38176. }
  38177. var depthSortedFacets = options.depthSortedFacets;
  38178. }
  38179. }
  38180. // facetPartitioning reinit if needed
  38181. var xSubRatio = 0;
  38182. var ySubRatio = 0;
  38183. var zSubRatio = 0;
  38184. var subSq = 0;
  38185. if (computeFacetPartitioning && options && options.bbSize) {
  38186. var ox = 0; // X partitioning index for facet position
  38187. var oy = 0; // Y partinioning index for facet position
  38188. var oz = 0; // Z partinioning index for facet position
  38189. var b1x = 0; // X partitioning index for facet v1 vertex
  38190. var b1y = 0; // Y partitioning index for facet v1 vertex
  38191. var b1z = 0; // z partitioning index for facet v1 vertex
  38192. var b2x = 0; // X partitioning index for facet v2 vertex
  38193. var b2y = 0; // Y partitioning index for facet v2 vertex
  38194. var b2z = 0; // Z partitioning index for facet v2 vertex
  38195. var b3x = 0; // X partitioning index for facet v3 vertex
  38196. var b3y = 0; // Y partitioning index for facet v3 vertex
  38197. var b3z = 0; // Z partitioning index for facet v3 vertex
  38198. var block_idx_o = 0; // facet barycenter block index
  38199. var block_idx_v1 = 0; // v1 vertex block index
  38200. var block_idx_v2 = 0; // v2 vertex block index
  38201. var block_idx_v3 = 0; // v3 vertex block index
  38202. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38203. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38204. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38205. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38206. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38207. subSq = options.subDiv.max * options.subDiv.max;
  38208. options.facetPartitioning.length = 0;
  38209. }
  38210. // reset the normals
  38211. for (index = 0; index < positions.length; index++) {
  38212. normals[index] = 0.0;
  38213. }
  38214. // Loop : 1 indice triplet = 1 facet
  38215. var nbFaces = (indices.length / 3) | 0;
  38216. for (index = 0; index < nbFaces; index++) {
  38217. // get the indexes of the coordinates of each vertex of the facet
  38218. v1x = indices[index * 3] * 3;
  38219. v1y = v1x + 1;
  38220. v1z = v1x + 2;
  38221. v2x = indices[index * 3 + 1] * 3;
  38222. v2y = v2x + 1;
  38223. v2z = v2x + 2;
  38224. v3x = indices[index * 3 + 2] * 3;
  38225. v3y = v3x + 1;
  38226. v3z = v3x + 2;
  38227. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38228. p1p2y = positions[v1y] - positions[v2y];
  38229. p1p2z = positions[v1z] - positions[v2z];
  38230. p3p2x = positions[v3x] - positions[v2x];
  38231. p3p2y = positions[v3y] - positions[v2y];
  38232. p3p2z = positions[v3z] - positions[v2z];
  38233. // compute the face normal with the cross product
  38234. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38235. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38236. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38237. // normalize this normal and store it in the array facetData
  38238. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38239. length = (length === 0) ? 1.0 : length;
  38240. faceNormalx /= length;
  38241. faceNormaly /= length;
  38242. faceNormalz /= length;
  38243. if (computeFacetNormals && options) {
  38244. options.facetNormals[index].x = faceNormalx;
  38245. options.facetNormals[index].y = faceNormaly;
  38246. options.facetNormals[index].z = faceNormalz;
  38247. }
  38248. if (computeFacetPositions && options) {
  38249. // compute and the facet barycenter coordinates in the array facetPositions
  38250. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38251. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38252. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38253. }
  38254. if (computeFacetPartitioning && options) {
  38255. // store the facet indexes in arrays in the main facetPartitioning array :
  38256. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38257. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38258. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38259. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38260. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38261. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38262. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38263. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38264. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38265. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38266. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38267. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38268. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38269. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38270. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38271. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38272. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38273. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38274. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38275. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38276. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38277. // push each facet index in each block containing the vertex
  38278. options.facetPartitioning[block_idx_v1].push(index);
  38279. if (block_idx_v2 != block_idx_v1) {
  38280. options.facetPartitioning[block_idx_v2].push(index);
  38281. }
  38282. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38283. options.facetPartitioning[block_idx_v3].push(index);
  38284. }
  38285. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38286. options.facetPartitioning[block_idx_o].push(index);
  38287. }
  38288. }
  38289. if (computeDepthSort && options && options.facetPositions) {
  38290. var dsf = depthSortedFacets[index];
  38291. dsf.ind = index * 3;
  38292. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38293. }
  38294. // compute the normals anyway
  38295. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38296. normals[v1y] += faceNormaly;
  38297. normals[v1z] += faceNormalz;
  38298. normals[v2x] += faceNormalx;
  38299. normals[v2y] += faceNormaly;
  38300. normals[v2z] += faceNormalz;
  38301. normals[v3x] += faceNormalx;
  38302. normals[v3y] += faceNormaly;
  38303. normals[v3z] += faceNormalz;
  38304. }
  38305. // last normalization of each normal
  38306. for (index = 0; index < normals.length / 3; index++) {
  38307. faceNormalx = normals[index * 3];
  38308. faceNormaly = normals[index * 3 + 1];
  38309. faceNormalz = normals[index * 3 + 2];
  38310. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38311. length = (length === 0) ? 1.0 : length;
  38312. faceNormalx /= length;
  38313. faceNormaly /= length;
  38314. faceNormalz /= length;
  38315. normals[index * 3] = faceNormalx;
  38316. normals[index * 3 + 1] = faceNormaly;
  38317. normals[index * 3 + 2] = faceNormalz;
  38318. }
  38319. };
  38320. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38321. var li = indices.length;
  38322. var ln = normals.length;
  38323. var i;
  38324. var n;
  38325. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38326. switch (sideOrientation) {
  38327. case BABYLON.Mesh.FRONTSIDE:
  38328. // nothing changed
  38329. break;
  38330. case BABYLON.Mesh.BACKSIDE:
  38331. var tmp;
  38332. // indices
  38333. for (i = 0; i < li; i += 3) {
  38334. tmp = indices[i];
  38335. indices[i] = indices[i + 2];
  38336. indices[i + 2] = tmp;
  38337. }
  38338. // normals
  38339. for (n = 0; n < ln; n++) {
  38340. normals[n] = -normals[n];
  38341. }
  38342. break;
  38343. case BABYLON.Mesh.DOUBLESIDE:
  38344. // positions
  38345. var lp = positions.length;
  38346. var l = lp / 3;
  38347. for (var p = 0; p < lp; p++) {
  38348. positions[lp + p] = positions[p];
  38349. }
  38350. // indices
  38351. for (i = 0; i < li; i += 3) {
  38352. indices[i + li] = indices[i + 2] + l;
  38353. indices[i + 1 + li] = indices[i + 1] + l;
  38354. indices[i + 2 + li] = indices[i] + l;
  38355. }
  38356. // normals
  38357. for (n = 0; n < ln; n++) {
  38358. normals[ln + n] = -normals[n];
  38359. }
  38360. // uvs
  38361. var lu = uvs.length;
  38362. var u = 0;
  38363. for (u = 0; u < lu; u++) {
  38364. uvs[u + lu] = uvs[u];
  38365. }
  38366. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38367. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38368. u = 0;
  38369. for (i = 0; i < lu / 2; i++) {
  38370. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38371. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38372. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38373. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38374. u += 2;
  38375. }
  38376. break;
  38377. }
  38378. };
  38379. /**
  38380. * Applies VertexData created from the imported parameters to the geometry
  38381. * @param parsedVertexData the parsed data from an imported file
  38382. * @param geometry the geometry to apply the VertexData to
  38383. */
  38384. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38385. var vertexData = new VertexData();
  38386. // positions
  38387. var positions = parsedVertexData.positions;
  38388. if (positions) {
  38389. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38390. }
  38391. // normals
  38392. var normals = parsedVertexData.normals;
  38393. if (normals) {
  38394. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38395. }
  38396. // tangents
  38397. var tangents = parsedVertexData.tangents;
  38398. if (tangents) {
  38399. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38400. }
  38401. // uvs
  38402. var uvs = parsedVertexData.uvs;
  38403. if (uvs) {
  38404. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38405. }
  38406. // uv2s
  38407. var uv2s = parsedVertexData.uv2s;
  38408. if (uv2s) {
  38409. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38410. }
  38411. // uv3s
  38412. var uv3s = parsedVertexData.uv3s;
  38413. if (uv3s) {
  38414. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38415. }
  38416. // uv4s
  38417. var uv4s = parsedVertexData.uv4s;
  38418. if (uv4s) {
  38419. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38420. }
  38421. // uv5s
  38422. var uv5s = parsedVertexData.uv5s;
  38423. if (uv5s) {
  38424. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38425. }
  38426. // uv6s
  38427. var uv6s = parsedVertexData.uv6s;
  38428. if (uv6s) {
  38429. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38430. }
  38431. // colors
  38432. var colors = parsedVertexData.colors;
  38433. if (colors) {
  38434. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38435. }
  38436. // matricesIndices
  38437. var matricesIndices = parsedVertexData.matricesIndices;
  38438. if (matricesIndices) {
  38439. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38440. }
  38441. // matricesWeights
  38442. var matricesWeights = parsedVertexData.matricesWeights;
  38443. if (matricesWeights) {
  38444. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38445. }
  38446. // indices
  38447. var indices = parsedVertexData.indices;
  38448. if (indices) {
  38449. vertexData.indices = indices;
  38450. }
  38451. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38452. };
  38453. return VertexData;
  38454. }());
  38455. BABYLON.VertexData = VertexData;
  38456. })(BABYLON || (BABYLON = {}));
  38457. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38458. var BABYLON;
  38459. (function (BABYLON) {
  38460. /**
  38461. * Class used to store geometry data (vertex buffers + index buffer)
  38462. */
  38463. var Geometry = /** @class */ (function () {
  38464. /**
  38465. * Creates a new geometry
  38466. * @param id defines the unique ID
  38467. * @param scene defines the hosting scene
  38468. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38469. * @param updatable defines if geometry must be updatable (false by default)
  38470. * @param mesh defines the mesh that will be associated with the geometry
  38471. */
  38472. function Geometry(id, scene, vertexData, updatable, mesh) {
  38473. if (updatable === void 0) { updatable = false; }
  38474. if (mesh === void 0) { mesh = null; }
  38475. /**
  38476. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38477. */
  38478. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38479. this._totalVertices = 0;
  38480. this._isDisposed = false;
  38481. this._indexBufferIsUpdatable = false;
  38482. this.id = id;
  38483. this._engine = scene.getEngine();
  38484. this._meshes = [];
  38485. this._scene = scene;
  38486. //Init vertex buffer cache
  38487. this._vertexBuffers = {};
  38488. this._indices = [];
  38489. this._updatable = updatable;
  38490. // vertexData
  38491. if (vertexData) {
  38492. this.setAllVerticesData(vertexData, updatable);
  38493. }
  38494. else {
  38495. this._totalVertices = 0;
  38496. this._indices = [];
  38497. }
  38498. if (this._engine.getCaps().vertexArrayObject) {
  38499. this._vertexArrayObjects = {};
  38500. }
  38501. // applyToMesh
  38502. if (mesh) {
  38503. if (mesh.getClassName() === "LinesMesh") {
  38504. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38505. this._updateExtend();
  38506. }
  38507. this.applyToMesh(mesh);
  38508. mesh.computeWorldMatrix(true);
  38509. }
  38510. }
  38511. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38512. /**
  38513. * 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
  38514. */
  38515. get: function () {
  38516. return this._boundingBias;
  38517. },
  38518. /**
  38519. * 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
  38520. */
  38521. set: function (value) {
  38522. if (this._boundingBias && this._boundingBias.equals(value)) {
  38523. return;
  38524. }
  38525. this._boundingBias = value.clone();
  38526. this._updateBoundingInfo(true, null);
  38527. },
  38528. enumerable: true,
  38529. configurable: true
  38530. });
  38531. /**
  38532. * Static function used to attach a new empty geometry to a mesh
  38533. * @param mesh defines the mesh to attach the geometry to
  38534. * @returns the new {BABYLON.Geometry}
  38535. */
  38536. Geometry.CreateGeometryForMesh = function (mesh) {
  38537. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38538. geometry.applyToMesh(mesh);
  38539. return geometry;
  38540. };
  38541. Object.defineProperty(Geometry.prototype, "extend", {
  38542. /**
  38543. * Gets the current extend of the geometry
  38544. */
  38545. get: function () {
  38546. return this._extend;
  38547. },
  38548. enumerable: true,
  38549. configurable: true
  38550. });
  38551. /**
  38552. * Gets the hosting scene
  38553. * @returns the hosting {BABYLON.Scene}
  38554. */
  38555. Geometry.prototype.getScene = function () {
  38556. return this._scene;
  38557. };
  38558. /**
  38559. * Gets the hosting engine
  38560. * @returns the hosting {BABYLON.Engine}
  38561. */
  38562. Geometry.prototype.getEngine = function () {
  38563. return this._engine;
  38564. };
  38565. /**
  38566. * Defines if the geometry is ready to use
  38567. * @returns true if the geometry is ready to be used
  38568. */
  38569. Geometry.prototype.isReady = function () {
  38570. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38571. };
  38572. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38573. /**
  38574. * Gets a value indicating that the geometry should not be serialized
  38575. */
  38576. get: function () {
  38577. for (var index = 0; index < this._meshes.length; index++) {
  38578. if (!this._meshes[index].doNotSerialize) {
  38579. return false;
  38580. }
  38581. }
  38582. return true;
  38583. },
  38584. enumerable: true,
  38585. configurable: true
  38586. });
  38587. /** @hidden */
  38588. Geometry.prototype._rebuild = function () {
  38589. if (this._vertexArrayObjects) {
  38590. this._vertexArrayObjects = {};
  38591. }
  38592. // Index buffer
  38593. if (this._meshes.length !== 0 && this._indices) {
  38594. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38595. }
  38596. // Vertex buffers
  38597. for (var key in this._vertexBuffers) {
  38598. var vertexBuffer = this._vertexBuffers[key];
  38599. vertexBuffer._rebuild();
  38600. }
  38601. };
  38602. /**
  38603. * Affects all geometry data in one call
  38604. * @param vertexData defines the geometry data
  38605. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38606. */
  38607. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38608. vertexData.applyToGeometry(this, updatable);
  38609. this.notifyUpdate();
  38610. };
  38611. /**
  38612. * Set specific vertex data
  38613. * @param kind defines the data kind (Position, normal, etc...)
  38614. * @param data defines the vertex data to use
  38615. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38616. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38617. */
  38618. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38619. if (updatable === void 0) { updatable = false; }
  38620. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38621. this.setVerticesBuffer(buffer);
  38622. };
  38623. /**
  38624. * Removes a specific vertex data
  38625. * @param kind defines the data kind (Position, normal, etc...)
  38626. */
  38627. Geometry.prototype.removeVerticesData = function (kind) {
  38628. if (this._vertexBuffers[kind]) {
  38629. this._vertexBuffers[kind].dispose();
  38630. delete this._vertexBuffers[kind];
  38631. }
  38632. };
  38633. /**
  38634. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38635. * @param buffer defines the vertex buffer to use
  38636. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38637. */
  38638. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38639. if (totalVertices === void 0) { totalVertices = null; }
  38640. var kind = buffer.getKind();
  38641. if (this._vertexBuffers[kind]) {
  38642. this._vertexBuffers[kind].dispose();
  38643. }
  38644. this._vertexBuffers[kind] = buffer;
  38645. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38646. var data = buffer.getData();
  38647. if (totalVertices != null) {
  38648. this._totalVertices = totalVertices;
  38649. }
  38650. else {
  38651. if (data != null) {
  38652. this._totalVertices = data.length / (buffer.byteStride / 4);
  38653. }
  38654. }
  38655. this._updateExtend(data);
  38656. this._resetPointsArrayCache();
  38657. var meshes = this._meshes;
  38658. var numOfMeshes = meshes.length;
  38659. for (var index = 0; index < numOfMeshes; index++) {
  38660. var mesh = meshes[index];
  38661. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38662. mesh._createGlobalSubMesh(false);
  38663. mesh.computeWorldMatrix(true);
  38664. }
  38665. }
  38666. this.notifyUpdate(kind);
  38667. if (this._vertexArrayObjects) {
  38668. this._disposeVertexArrayObjects();
  38669. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38670. }
  38671. };
  38672. /**
  38673. * Update a specific vertex buffer
  38674. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38675. * It will do nothing if the buffer is not updatable
  38676. * @param kind defines the data kind (Position, normal, etc...)
  38677. * @param data defines the data to use
  38678. * @param offset defines the offset in the target buffer where to store the data
  38679. * @param useBytes set to true if the offset is in bytes
  38680. */
  38681. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38682. if (useBytes === void 0) { useBytes = false; }
  38683. var vertexBuffer = this.getVertexBuffer(kind);
  38684. if (!vertexBuffer) {
  38685. return;
  38686. }
  38687. vertexBuffer.updateDirectly(data, offset, useBytes);
  38688. this.notifyUpdate(kind);
  38689. };
  38690. /**
  38691. * Update a specific vertex buffer
  38692. * This function will create a new buffer if the current one is not updatable
  38693. * @param kind defines the data kind (Position, normal, etc...)
  38694. * @param data defines the data to use
  38695. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38696. */
  38697. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38698. if (updateExtends === void 0) { updateExtends = false; }
  38699. var vertexBuffer = this.getVertexBuffer(kind);
  38700. if (!vertexBuffer) {
  38701. return;
  38702. }
  38703. vertexBuffer.update(data);
  38704. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38705. this._updateBoundingInfo(updateExtends, data);
  38706. }
  38707. this.notifyUpdate(kind);
  38708. };
  38709. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38710. if (updateExtends) {
  38711. this._updateExtend(data);
  38712. }
  38713. var meshes = this._meshes;
  38714. var numOfMeshes = meshes.length;
  38715. this._resetPointsArrayCache();
  38716. for (var index = 0; index < numOfMeshes; index++) {
  38717. var mesh = meshes[index];
  38718. if (updateExtends) {
  38719. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38720. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38721. var subMesh = mesh.subMeshes[subIndex];
  38722. subMesh.refreshBoundingInfo();
  38723. }
  38724. }
  38725. }
  38726. };
  38727. /** @hidden */
  38728. Geometry.prototype._bind = function (effect, indexToBind) {
  38729. if (!effect) {
  38730. return;
  38731. }
  38732. if (indexToBind === undefined) {
  38733. indexToBind = this._indexBuffer;
  38734. }
  38735. var vbs = this.getVertexBuffers();
  38736. if (!vbs) {
  38737. return;
  38738. }
  38739. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38740. this._engine.bindBuffers(vbs, indexToBind, effect);
  38741. return;
  38742. }
  38743. // Using VAO
  38744. if (!this._vertexArrayObjects[effect.key]) {
  38745. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38746. }
  38747. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38748. };
  38749. /**
  38750. * Gets total number of vertices
  38751. * @returns the total number of vertices
  38752. */
  38753. Geometry.prototype.getTotalVertices = function () {
  38754. if (!this.isReady()) {
  38755. return 0;
  38756. }
  38757. return this._totalVertices;
  38758. };
  38759. /**
  38760. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38761. * @param kind defines the data kind (Position, normal, etc...)
  38762. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38763. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38764. * @returns a float array containing vertex data
  38765. */
  38766. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38767. var vertexBuffer = this.getVertexBuffer(kind);
  38768. if (!vertexBuffer) {
  38769. return null;
  38770. }
  38771. var data = vertexBuffer.getData();
  38772. if (!data) {
  38773. return null;
  38774. }
  38775. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38776. var count = this._totalVertices * vertexBuffer.getSize();
  38777. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38778. var copy_1 = new Array(count);
  38779. vertexBuffer.forEach(count, function (value, index) {
  38780. copy_1[index] = value;
  38781. });
  38782. return copy_1;
  38783. }
  38784. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38785. if (data instanceof Array) {
  38786. var offset = vertexBuffer.byteOffset / 4;
  38787. return BABYLON.Tools.Slice(data, offset, offset + count);
  38788. }
  38789. else if (data instanceof ArrayBuffer) {
  38790. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38791. }
  38792. else {
  38793. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38794. }
  38795. }
  38796. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38797. return BABYLON.Tools.Slice(data);
  38798. }
  38799. return data;
  38800. };
  38801. /**
  38802. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38803. * @param kind defines the data kind (Position, normal, etc...)
  38804. * @returns true if the vertex buffer with the specified kind is updatable
  38805. */
  38806. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38807. var vb = this._vertexBuffers[kind];
  38808. if (!vb) {
  38809. return false;
  38810. }
  38811. return vb.isUpdatable();
  38812. };
  38813. /**
  38814. * Gets a specific vertex buffer
  38815. * @param kind defines the data kind (Position, normal, etc...)
  38816. * @returns a {BABYLON.VertexBuffer}
  38817. */
  38818. Geometry.prototype.getVertexBuffer = function (kind) {
  38819. if (!this.isReady()) {
  38820. return null;
  38821. }
  38822. return this._vertexBuffers[kind];
  38823. };
  38824. /**
  38825. * Returns all vertex buffers
  38826. * @return an object holding all vertex buffers indexed by kind
  38827. */
  38828. Geometry.prototype.getVertexBuffers = function () {
  38829. if (!this.isReady()) {
  38830. return null;
  38831. }
  38832. return this._vertexBuffers;
  38833. };
  38834. /**
  38835. * Gets a boolean indicating if specific vertex buffer is present
  38836. * @param kind defines the data kind (Position, normal, etc...)
  38837. * @returns true if data is present
  38838. */
  38839. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38840. if (!this._vertexBuffers) {
  38841. if (this._delayInfo) {
  38842. return this._delayInfo.indexOf(kind) !== -1;
  38843. }
  38844. return false;
  38845. }
  38846. return this._vertexBuffers[kind] !== undefined;
  38847. };
  38848. /**
  38849. * Gets a list of all attached data kinds (Position, normal, etc...)
  38850. * @returns a list of string containing all kinds
  38851. */
  38852. Geometry.prototype.getVerticesDataKinds = function () {
  38853. var result = [];
  38854. var kind;
  38855. if (!this._vertexBuffers && this._delayInfo) {
  38856. for (kind in this._delayInfo) {
  38857. result.push(kind);
  38858. }
  38859. }
  38860. else {
  38861. for (kind in this._vertexBuffers) {
  38862. result.push(kind);
  38863. }
  38864. }
  38865. return result;
  38866. };
  38867. /**
  38868. * Update index buffer
  38869. * @param indices defines the indices to store in the index buffer
  38870. * @param offset defines the offset in the target buffer where to store the data
  38871. */
  38872. Geometry.prototype.updateIndices = function (indices, offset) {
  38873. if (!this._indexBuffer) {
  38874. return;
  38875. }
  38876. if (!this._indexBufferIsUpdatable) {
  38877. this.setIndices(indices, null, true);
  38878. }
  38879. else {
  38880. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38881. }
  38882. };
  38883. /**
  38884. * Creates a new index buffer
  38885. * @param indices defines the indices to store in the index buffer
  38886. * @param totalVertices defines the total number of vertices (could be null)
  38887. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38888. */
  38889. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38890. if (totalVertices === void 0) { totalVertices = null; }
  38891. if (updatable === void 0) { updatable = false; }
  38892. if (this._indexBuffer) {
  38893. this._engine._releaseBuffer(this._indexBuffer);
  38894. }
  38895. this._disposeVertexArrayObjects();
  38896. this._indices = indices;
  38897. this._indexBufferIsUpdatable = updatable;
  38898. if (this._meshes.length !== 0 && this._indices) {
  38899. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38900. }
  38901. if (totalVertices != undefined) { // including null and undefined
  38902. this._totalVertices = totalVertices;
  38903. }
  38904. var meshes = this._meshes;
  38905. var numOfMeshes = meshes.length;
  38906. for (var index = 0; index < numOfMeshes; index++) {
  38907. meshes[index]._createGlobalSubMesh(true);
  38908. }
  38909. this.notifyUpdate();
  38910. };
  38911. /**
  38912. * Return the total number of indices
  38913. * @returns the total number of indices
  38914. */
  38915. Geometry.prototype.getTotalIndices = function () {
  38916. if (!this.isReady()) {
  38917. return 0;
  38918. }
  38919. return this._indices.length;
  38920. };
  38921. /**
  38922. * Gets the index buffer array
  38923. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38924. * @returns the index buffer array
  38925. */
  38926. Geometry.prototype.getIndices = function (copyWhenShared) {
  38927. if (!this.isReady()) {
  38928. return null;
  38929. }
  38930. var orig = this._indices;
  38931. if (!copyWhenShared || this._meshes.length === 1) {
  38932. return orig;
  38933. }
  38934. else {
  38935. var len = orig.length;
  38936. var copy = [];
  38937. for (var i = 0; i < len; i++) {
  38938. copy.push(orig[i]);
  38939. }
  38940. return copy;
  38941. }
  38942. };
  38943. /**
  38944. * Gets the index buffer
  38945. * @return the index buffer
  38946. */
  38947. Geometry.prototype.getIndexBuffer = function () {
  38948. if (!this.isReady()) {
  38949. return null;
  38950. }
  38951. return this._indexBuffer;
  38952. };
  38953. /** @hidden */
  38954. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38955. if (effect === void 0) { effect = null; }
  38956. if (!effect || !this._vertexArrayObjects) {
  38957. return;
  38958. }
  38959. if (this._vertexArrayObjects[effect.key]) {
  38960. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38961. delete this._vertexArrayObjects[effect.key];
  38962. }
  38963. };
  38964. /**
  38965. * Release the associated resources for a specific mesh
  38966. * @param mesh defines the source mesh
  38967. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38968. */
  38969. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38970. var meshes = this._meshes;
  38971. var index = meshes.indexOf(mesh);
  38972. if (index === -1) {
  38973. return;
  38974. }
  38975. meshes.splice(index, 1);
  38976. mesh._geometry = null;
  38977. if (meshes.length === 0 && shouldDispose) {
  38978. this.dispose();
  38979. }
  38980. };
  38981. /**
  38982. * Apply current geometry to a given mesh
  38983. * @param mesh defines the mesh to apply geometry to
  38984. */
  38985. Geometry.prototype.applyToMesh = function (mesh) {
  38986. if (mesh._geometry === this) {
  38987. return;
  38988. }
  38989. var previousGeometry = mesh._geometry;
  38990. if (previousGeometry) {
  38991. previousGeometry.releaseForMesh(mesh);
  38992. }
  38993. var meshes = this._meshes;
  38994. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38995. mesh._geometry = this;
  38996. this._scene.pushGeometry(this);
  38997. meshes.push(mesh);
  38998. if (this.isReady()) {
  38999. this._applyToMesh(mesh);
  39000. }
  39001. else {
  39002. mesh._boundingInfo = this._boundingInfo;
  39003. }
  39004. };
  39005. Geometry.prototype._updateExtend = function (data) {
  39006. if (data === void 0) { data = null; }
  39007. if (!data) {
  39008. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39009. }
  39010. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39011. };
  39012. Geometry.prototype._applyToMesh = function (mesh) {
  39013. var numOfMeshes = this._meshes.length;
  39014. // vertexBuffers
  39015. for (var kind in this._vertexBuffers) {
  39016. if (numOfMeshes === 1) {
  39017. this._vertexBuffers[kind].create();
  39018. }
  39019. var buffer = this._vertexBuffers[kind].getBuffer();
  39020. if (buffer)
  39021. buffer.references = numOfMeshes;
  39022. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39023. if (!this._extend) {
  39024. this._updateExtend();
  39025. }
  39026. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39027. mesh._createGlobalSubMesh(false);
  39028. //bounding info was just created again, world matrix should be applied again.
  39029. mesh._updateBoundingInfo();
  39030. }
  39031. }
  39032. // indexBuffer
  39033. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39034. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39035. }
  39036. if (this._indexBuffer) {
  39037. this._indexBuffer.references = numOfMeshes;
  39038. }
  39039. };
  39040. Geometry.prototype.notifyUpdate = function (kind) {
  39041. if (this.onGeometryUpdated) {
  39042. this.onGeometryUpdated(this, kind);
  39043. }
  39044. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39045. var mesh = _a[_i];
  39046. mesh._markSubMeshesAsAttributesDirty();
  39047. }
  39048. };
  39049. /**
  39050. * Load the geometry if it was flagged as delay loaded
  39051. * @param scene defines the hosting scene
  39052. * @param onLoaded defines a callback called when the geometry is loaded
  39053. */
  39054. Geometry.prototype.load = function (scene, onLoaded) {
  39055. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39056. return;
  39057. }
  39058. if (this.isReady()) {
  39059. if (onLoaded) {
  39060. onLoaded();
  39061. }
  39062. return;
  39063. }
  39064. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39065. this._queueLoad(scene, onLoaded);
  39066. };
  39067. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39068. var _this = this;
  39069. if (!this.delayLoadingFile) {
  39070. return;
  39071. }
  39072. scene._addPendingData(this);
  39073. scene._loadFile(this.delayLoadingFile, function (data) {
  39074. if (!_this._delayLoadingFunction) {
  39075. return;
  39076. }
  39077. _this._delayLoadingFunction(JSON.parse(data), _this);
  39078. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39079. _this._delayInfo = [];
  39080. scene._removePendingData(_this);
  39081. var meshes = _this._meshes;
  39082. var numOfMeshes = meshes.length;
  39083. for (var index = 0; index < numOfMeshes; index++) {
  39084. _this._applyToMesh(meshes[index]);
  39085. }
  39086. if (onLoaded) {
  39087. onLoaded();
  39088. }
  39089. }, undefined, true);
  39090. };
  39091. /**
  39092. * Invert the geometry to move from a right handed system to a left handed one.
  39093. */
  39094. Geometry.prototype.toLeftHanded = function () {
  39095. // Flip faces
  39096. var tIndices = this.getIndices(false);
  39097. if (tIndices != null && tIndices.length > 0) {
  39098. for (var i = 0; i < tIndices.length; i += 3) {
  39099. var tTemp = tIndices[i + 0];
  39100. tIndices[i + 0] = tIndices[i + 2];
  39101. tIndices[i + 2] = tTemp;
  39102. }
  39103. this.setIndices(tIndices);
  39104. }
  39105. // Negate position.z
  39106. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39107. if (tPositions != null && tPositions.length > 0) {
  39108. for (var i = 0; i < tPositions.length; i += 3) {
  39109. tPositions[i + 2] = -tPositions[i + 2];
  39110. }
  39111. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39112. }
  39113. // Negate normal.z
  39114. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39115. if (tNormals != null && tNormals.length > 0) {
  39116. for (var i = 0; i < tNormals.length; i += 3) {
  39117. tNormals[i + 2] = -tNormals[i + 2];
  39118. }
  39119. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39120. }
  39121. };
  39122. // Cache
  39123. /** @hidden */
  39124. Geometry.prototype._resetPointsArrayCache = function () {
  39125. this._positions = null;
  39126. };
  39127. /** @hidden */
  39128. Geometry.prototype._generatePointsArray = function () {
  39129. if (this._positions)
  39130. return true;
  39131. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39132. if (!data || data.length === 0) {
  39133. return false;
  39134. }
  39135. this._positions = [];
  39136. for (var index = 0; index < data.length; index += 3) {
  39137. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39138. }
  39139. return true;
  39140. };
  39141. /**
  39142. * Gets a value indicating if the geometry is disposed
  39143. * @returns true if the geometry was disposed
  39144. */
  39145. Geometry.prototype.isDisposed = function () {
  39146. return this._isDisposed;
  39147. };
  39148. Geometry.prototype._disposeVertexArrayObjects = function () {
  39149. if (this._vertexArrayObjects) {
  39150. for (var kind in this._vertexArrayObjects) {
  39151. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39152. }
  39153. this._vertexArrayObjects = {};
  39154. }
  39155. };
  39156. /**
  39157. * Free all associated resources
  39158. */
  39159. Geometry.prototype.dispose = function () {
  39160. var meshes = this._meshes;
  39161. var numOfMeshes = meshes.length;
  39162. var index;
  39163. for (index = 0; index < numOfMeshes; index++) {
  39164. this.releaseForMesh(meshes[index]);
  39165. }
  39166. this._meshes = [];
  39167. this._disposeVertexArrayObjects();
  39168. for (var kind in this._vertexBuffers) {
  39169. this._vertexBuffers[kind].dispose();
  39170. }
  39171. this._vertexBuffers = {};
  39172. this._totalVertices = 0;
  39173. if (this._indexBuffer) {
  39174. this._engine._releaseBuffer(this._indexBuffer);
  39175. }
  39176. this._indexBuffer = null;
  39177. this._indices = [];
  39178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39179. this.delayLoadingFile = null;
  39180. this._delayLoadingFunction = null;
  39181. this._delayInfo = [];
  39182. this._boundingInfo = null;
  39183. this._scene.removeGeometry(this);
  39184. this._isDisposed = true;
  39185. };
  39186. /**
  39187. * Clone the current geometry into a new geometry
  39188. * @param id defines the unique ID of the new geometry
  39189. * @returns a new geometry object
  39190. */
  39191. Geometry.prototype.copy = function (id) {
  39192. var vertexData = new BABYLON.VertexData();
  39193. vertexData.indices = [];
  39194. var indices = this.getIndices();
  39195. if (indices) {
  39196. for (var index = 0; index < indices.length; index++) {
  39197. vertexData.indices.push(indices[index]);
  39198. }
  39199. }
  39200. var updatable = false;
  39201. var stopChecking = false;
  39202. var kind;
  39203. for (kind in this._vertexBuffers) {
  39204. // using slice() to make a copy of the array and not just reference it
  39205. var data = this.getVerticesData(kind);
  39206. if (data instanceof Float32Array) {
  39207. vertexData.set(new Float32Array(data), kind);
  39208. }
  39209. else {
  39210. vertexData.set(data.slice(0), kind);
  39211. }
  39212. if (!stopChecking) {
  39213. var vb = this.getVertexBuffer(kind);
  39214. if (vb) {
  39215. updatable = vb.isUpdatable();
  39216. stopChecking = !updatable;
  39217. }
  39218. }
  39219. }
  39220. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39221. geometry.delayLoadState = this.delayLoadState;
  39222. geometry.delayLoadingFile = this.delayLoadingFile;
  39223. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39224. for (kind in this._delayInfo) {
  39225. geometry._delayInfo = geometry._delayInfo || [];
  39226. geometry._delayInfo.push(kind);
  39227. }
  39228. // Bounding info
  39229. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39230. return geometry;
  39231. };
  39232. /**
  39233. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39234. * @return a JSON representation of the current geometry data (without the vertices data)
  39235. */
  39236. Geometry.prototype.serialize = function () {
  39237. var serializationObject = {};
  39238. serializationObject.id = this.id;
  39239. serializationObject.updatable = this._updatable;
  39240. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39241. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39242. }
  39243. return serializationObject;
  39244. };
  39245. Geometry.prototype.toNumberArray = function (origin) {
  39246. if (Array.isArray(origin)) {
  39247. return origin;
  39248. }
  39249. else {
  39250. return Array.prototype.slice.call(origin);
  39251. }
  39252. };
  39253. /**
  39254. * Serialize all vertices data into a JSON oject
  39255. * @returns a JSON representation of the current geometry data
  39256. */
  39257. Geometry.prototype.serializeVerticeData = function () {
  39258. var serializationObject = this.serialize();
  39259. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39260. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39261. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39262. serializationObject.positions._updatable = true;
  39263. }
  39264. }
  39265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39266. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39267. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39268. serializationObject.normals._updatable = true;
  39269. }
  39270. }
  39271. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39272. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39273. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39274. serializationObject.tangets._updatable = true;
  39275. }
  39276. }
  39277. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39278. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39279. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39280. serializationObject.uvs._updatable = true;
  39281. }
  39282. }
  39283. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39284. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39285. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39286. serializationObject.uv2s._updatable = true;
  39287. }
  39288. }
  39289. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39290. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39291. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39292. serializationObject.uv3s._updatable = true;
  39293. }
  39294. }
  39295. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39296. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39297. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39298. serializationObject.uv4s._updatable = true;
  39299. }
  39300. }
  39301. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39302. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39303. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39304. serializationObject.uv5s._updatable = true;
  39305. }
  39306. }
  39307. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39308. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39309. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39310. serializationObject.uv6s._updatable = true;
  39311. }
  39312. }
  39313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39314. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39315. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39316. serializationObject.colors._updatable = true;
  39317. }
  39318. }
  39319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39320. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39321. serializationObject.matricesIndices._isExpanded = true;
  39322. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39323. serializationObject.matricesIndices._updatable = true;
  39324. }
  39325. }
  39326. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39327. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39328. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39329. serializationObject.matricesWeights._updatable = true;
  39330. }
  39331. }
  39332. serializationObject.indices = this.toNumberArray(this.getIndices());
  39333. return serializationObject;
  39334. };
  39335. // Statics
  39336. /**
  39337. * Extracts a clone of a mesh geometry
  39338. * @param mesh defines the source mesh
  39339. * @param id defines the unique ID of the new geometry object
  39340. * @returns the new geometry object
  39341. */
  39342. Geometry.ExtractFromMesh = function (mesh, id) {
  39343. var geometry = mesh._geometry;
  39344. if (!geometry) {
  39345. return null;
  39346. }
  39347. return geometry.copy(id);
  39348. };
  39349. /**
  39350. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39351. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39352. * Be aware Math.random() could cause collisions, but:
  39353. * "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"
  39354. * @returns a string containing a new GUID
  39355. */
  39356. Geometry.RandomId = function () {
  39357. return BABYLON.Tools.RandomId();
  39358. };
  39359. /** @hidden */
  39360. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39361. var scene = mesh.getScene();
  39362. // Geometry
  39363. var geometryId = parsedGeometry.geometryId;
  39364. if (geometryId) {
  39365. var geometry = scene.getGeometryByID(geometryId);
  39366. if (geometry) {
  39367. geometry.applyToMesh(mesh);
  39368. }
  39369. }
  39370. else if (parsedGeometry instanceof ArrayBuffer) {
  39371. var binaryInfo = mesh._binaryInfo;
  39372. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39373. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39374. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39375. }
  39376. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39377. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39378. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39379. }
  39380. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39381. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39382. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39383. }
  39384. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39385. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39386. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39387. }
  39388. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39389. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39390. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39391. }
  39392. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39393. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39394. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39395. }
  39396. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39397. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39398. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39399. }
  39400. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39401. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39402. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39403. }
  39404. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39405. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39406. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39407. }
  39408. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39409. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39410. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39411. }
  39412. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39413. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39414. var floatIndices = [];
  39415. for (var i = 0; i < matricesIndicesData.length; i++) {
  39416. var index = matricesIndicesData[i];
  39417. floatIndices.push(index & 0x000000FF);
  39418. floatIndices.push((index & 0x0000FF00) >> 8);
  39419. floatIndices.push((index & 0x00FF0000) >> 16);
  39420. floatIndices.push(index >> 24);
  39421. }
  39422. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39423. }
  39424. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39425. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39426. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39427. }
  39428. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39429. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39430. mesh.setIndices(indicesData, null);
  39431. }
  39432. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39433. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39434. mesh.subMeshes = [];
  39435. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39436. var materialIndex = subMeshesData[(i * 5) + 0];
  39437. var verticesStart = subMeshesData[(i * 5) + 1];
  39438. var verticesCount = subMeshesData[(i * 5) + 2];
  39439. var indexStart = subMeshesData[(i * 5) + 3];
  39440. var indexCount = subMeshesData[(i * 5) + 4];
  39441. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39442. }
  39443. }
  39444. }
  39445. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39446. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39447. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39448. if (parsedGeometry.tangents) {
  39449. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39450. }
  39451. if (parsedGeometry.uvs) {
  39452. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39453. }
  39454. if (parsedGeometry.uvs2) {
  39455. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39456. }
  39457. if (parsedGeometry.uvs3) {
  39458. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39459. }
  39460. if (parsedGeometry.uvs4) {
  39461. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39462. }
  39463. if (parsedGeometry.uvs5) {
  39464. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39465. }
  39466. if (parsedGeometry.uvs6) {
  39467. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39468. }
  39469. if (parsedGeometry.colors) {
  39470. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39471. }
  39472. if (parsedGeometry.matricesIndices) {
  39473. if (!parsedGeometry.matricesIndices._isExpanded) {
  39474. var floatIndices = [];
  39475. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39476. var matricesIndex = parsedGeometry.matricesIndices[i];
  39477. floatIndices.push(matricesIndex & 0x000000FF);
  39478. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39479. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39480. floatIndices.push(matricesIndex >> 24);
  39481. }
  39482. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39483. }
  39484. else {
  39485. delete parsedGeometry.matricesIndices._isExpanded;
  39486. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39487. }
  39488. }
  39489. if (parsedGeometry.matricesIndicesExtra) {
  39490. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39491. var floatIndices = [];
  39492. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39493. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39494. floatIndices.push(matricesIndex & 0x000000FF);
  39495. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39496. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39497. floatIndices.push(matricesIndex >> 24);
  39498. }
  39499. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39500. }
  39501. else {
  39502. delete parsedGeometry.matricesIndices._isExpanded;
  39503. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39504. }
  39505. }
  39506. if (parsedGeometry.matricesWeights) {
  39507. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39508. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39509. }
  39510. if (parsedGeometry.matricesWeightsExtra) {
  39511. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39512. }
  39513. mesh.setIndices(parsedGeometry.indices, null);
  39514. }
  39515. // SubMeshes
  39516. if (parsedGeometry.subMeshes) {
  39517. mesh.subMeshes = [];
  39518. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39519. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39520. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39521. }
  39522. }
  39523. // Flat shading
  39524. if (mesh._shouldGenerateFlatShading) {
  39525. mesh.convertToFlatShadedMesh();
  39526. delete mesh._shouldGenerateFlatShading;
  39527. }
  39528. // Update
  39529. mesh.computeWorldMatrix(true);
  39530. // Octree
  39531. var sceneOctree = scene.selectionOctree;
  39532. if (sceneOctree !== undefined && sceneOctree !== null) {
  39533. sceneOctree.addMesh(mesh);
  39534. }
  39535. };
  39536. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39537. var epsilon = 1e-3;
  39538. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39539. return;
  39540. }
  39541. var noInfluenceBoneIndex = 0.0;
  39542. if (parsedGeometry.skeletonId > -1) {
  39543. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39544. if (!skeleton) {
  39545. return;
  39546. }
  39547. noInfluenceBoneIndex = skeleton.bones.length;
  39548. }
  39549. else {
  39550. return;
  39551. }
  39552. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39553. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39554. var matricesWeights = parsedGeometry.matricesWeights;
  39555. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39556. var influencers = parsedGeometry.numBoneInfluencer;
  39557. var size = matricesWeights.length;
  39558. for (var i = 0; i < size; i += 4) {
  39559. var weight = 0.0;
  39560. var firstZeroWeight = -1;
  39561. for (var j = 0; j < 4; j++) {
  39562. var w = matricesWeights[i + j];
  39563. weight += w;
  39564. if (w < epsilon && firstZeroWeight < 0) {
  39565. firstZeroWeight = j;
  39566. }
  39567. }
  39568. if (matricesWeightsExtra) {
  39569. for (var j = 0; j < 4; j++) {
  39570. var w = matricesWeightsExtra[i + j];
  39571. weight += w;
  39572. if (w < epsilon && firstZeroWeight < 0) {
  39573. firstZeroWeight = j + 4;
  39574. }
  39575. }
  39576. }
  39577. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39578. firstZeroWeight = influencers - 1;
  39579. }
  39580. if (weight > epsilon) {
  39581. var mweight = 1.0 / weight;
  39582. for (var j = 0; j < 4; j++) {
  39583. matricesWeights[i + j] *= mweight;
  39584. }
  39585. if (matricesWeightsExtra) {
  39586. for (var j = 0; j < 4; j++) {
  39587. matricesWeightsExtra[i + j] *= mweight;
  39588. }
  39589. }
  39590. }
  39591. else {
  39592. if (firstZeroWeight >= 4) {
  39593. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39594. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39595. }
  39596. else {
  39597. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39598. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39599. }
  39600. }
  39601. }
  39602. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39603. if (parsedGeometry.matricesWeightsExtra) {
  39604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39605. }
  39606. };
  39607. /**
  39608. * Create a new geometry from persisted data (Using .babylon file format)
  39609. * @param parsedVertexData defines the persisted data
  39610. * @param scene defines the hosting scene
  39611. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39612. * @returns the new geometry object
  39613. */
  39614. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39615. if (scene.getGeometryByID(parsedVertexData.id)) {
  39616. return null; // null since geometry could be something else than a box...
  39617. }
  39618. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39619. if (BABYLON.Tags) {
  39620. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39621. }
  39622. if (parsedVertexData.delayLoadingFile) {
  39623. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39624. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39625. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39626. geometry._delayInfo = [];
  39627. if (parsedVertexData.hasUVs) {
  39628. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39629. }
  39630. if (parsedVertexData.hasUVs2) {
  39631. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39632. }
  39633. if (parsedVertexData.hasUVs3) {
  39634. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39635. }
  39636. if (parsedVertexData.hasUVs4) {
  39637. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39638. }
  39639. if (parsedVertexData.hasUVs5) {
  39640. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39641. }
  39642. if (parsedVertexData.hasUVs6) {
  39643. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39644. }
  39645. if (parsedVertexData.hasColors) {
  39646. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39647. }
  39648. if (parsedVertexData.hasMatricesIndices) {
  39649. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39650. }
  39651. if (parsedVertexData.hasMatricesWeights) {
  39652. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39653. }
  39654. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39655. }
  39656. else {
  39657. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39658. }
  39659. scene.pushGeometry(geometry, true);
  39660. return geometry;
  39661. };
  39662. return Geometry;
  39663. }());
  39664. BABYLON.Geometry = Geometry;
  39665. // Primitives
  39666. /// Abstract class
  39667. /**
  39668. * Abstract class used to provide common services for all typed geometries
  39669. * @hidden
  39670. */
  39671. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39672. __extends(_PrimitiveGeometry, _super);
  39673. /**
  39674. * Creates a new typed geometry
  39675. * @param id defines the unique ID of the geometry
  39676. * @param scene defines the hosting scene
  39677. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39678. * @param mesh defines the hosting mesh (can be null)
  39679. */
  39680. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39681. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39682. if (mesh === void 0) { mesh = null; }
  39683. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39684. _this._canBeRegenerated = _canBeRegenerated;
  39685. _this._beingRegenerated = true;
  39686. _this.regenerate();
  39687. _this._beingRegenerated = false;
  39688. return _this;
  39689. }
  39690. /**
  39691. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39692. * @returns true if the geometry can be regenerated
  39693. */
  39694. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39695. return this._canBeRegenerated;
  39696. };
  39697. /**
  39698. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39699. */
  39700. _PrimitiveGeometry.prototype.regenerate = function () {
  39701. if (!this._canBeRegenerated) {
  39702. return;
  39703. }
  39704. this._beingRegenerated = true;
  39705. this.setAllVerticesData(this._regenerateVertexData(), false);
  39706. this._beingRegenerated = false;
  39707. };
  39708. /**
  39709. * Clone the geometry
  39710. * @param id defines the unique ID of the new geometry
  39711. * @returns the new geometry
  39712. */
  39713. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39714. return _super.prototype.copy.call(this, id);
  39715. };
  39716. // overrides
  39717. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39718. if (!this._beingRegenerated) {
  39719. return;
  39720. }
  39721. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39722. };
  39723. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39724. if (!this._beingRegenerated) {
  39725. return;
  39726. }
  39727. _super.prototype.setVerticesData.call(this, kind, data, false);
  39728. };
  39729. // to override
  39730. /** @hidden */
  39731. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39732. throw new Error("Abstract method");
  39733. };
  39734. _PrimitiveGeometry.prototype.copy = function (id) {
  39735. throw new Error("Must be overriden in sub-classes.");
  39736. };
  39737. _PrimitiveGeometry.prototype.serialize = function () {
  39738. var serializationObject = _super.prototype.serialize.call(this);
  39739. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39740. return serializationObject;
  39741. };
  39742. return _PrimitiveGeometry;
  39743. }(Geometry));
  39744. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39745. /**
  39746. * Creates a ribbon geometry
  39747. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39748. */
  39749. var RibbonGeometry = /** @class */ (function (_super) {
  39750. __extends(RibbonGeometry, _super);
  39751. /**
  39752. * Creates a ribbon geometry
  39753. * @param id defines the unique ID of the geometry
  39754. * @param scene defines the hosting scene
  39755. * @param pathArray defines the array of paths to use
  39756. * @param closeArray defines if the last path and the first path must be joined
  39757. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39758. * @param offset defines the offset between points
  39759. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39760. * @param mesh defines the hosting mesh (can be null)
  39761. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39762. */
  39763. function RibbonGeometry(id, scene,
  39764. /**
  39765. * Defines the array of paths to use
  39766. */
  39767. pathArray,
  39768. /**
  39769. * Defines if the last and first points of each path in your pathArray must be joined
  39770. */
  39771. closeArray,
  39772. /**
  39773. * Defines if the last and first points of each path in your pathArray must be joined
  39774. */
  39775. closePath,
  39776. /**
  39777. * Defines the offset between points
  39778. */
  39779. offset, canBeRegenerated, mesh,
  39780. /**
  39781. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39782. */
  39783. side) {
  39784. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39785. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39786. _this.pathArray = pathArray;
  39787. _this.closeArray = closeArray;
  39788. _this.closePath = closePath;
  39789. _this.offset = offset;
  39790. _this.side = side;
  39791. return _this;
  39792. }
  39793. /** @hidden */
  39794. RibbonGeometry.prototype._regenerateVertexData = function () {
  39795. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39796. };
  39797. RibbonGeometry.prototype.copy = function (id) {
  39798. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39799. };
  39800. return RibbonGeometry;
  39801. }(_PrimitiveGeometry));
  39802. BABYLON.RibbonGeometry = RibbonGeometry;
  39803. /**
  39804. * Creates a box geometry
  39805. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39806. */
  39807. var BoxGeometry = /** @class */ (function (_super) {
  39808. __extends(BoxGeometry, _super);
  39809. /**
  39810. * Creates a box geometry
  39811. * @param id defines the unique ID of the geometry
  39812. * @param scene defines the hosting scene
  39813. * @param size defines the zise of the box (width, height and depth are the same)
  39814. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39815. * @param mesh defines the hosting mesh (can be null)
  39816. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39817. */
  39818. function BoxGeometry(id, scene,
  39819. /**
  39820. * Defines the zise of the box (width, height and depth are the same)
  39821. */
  39822. size, canBeRegenerated, mesh,
  39823. /**
  39824. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39825. */
  39826. side) {
  39827. if (mesh === void 0) { mesh = null; }
  39828. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39829. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39830. _this.size = size;
  39831. _this.side = side;
  39832. return _this;
  39833. }
  39834. BoxGeometry.prototype._regenerateVertexData = function () {
  39835. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39836. };
  39837. BoxGeometry.prototype.copy = function (id) {
  39838. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39839. };
  39840. BoxGeometry.prototype.serialize = function () {
  39841. var serializationObject = _super.prototype.serialize.call(this);
  39842. serializationObject.size = this.size;
  39843. return serializationObject;
  39844. };
  39845. BoxGeometry.Parse = function (parsedBox, scene) {
  39846. if (scene.getGeometryByID(parsedBox.id)) {
  39847. return null; // null since geometry could be something else than a box...
  39848. }
  39849. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39850. if (BABYLON.Tags) {
  39851. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39852. }
  39853. scene.pushGeometry(box, true);
  39854. return box;
  39855. };
  39856. return BoxGeometry;
  39857. }(_PrimitiveGeometry));
  39858. BABYLON.BoxGeometry = BoxGeometry;
  39859. /**
  39860. * Creates a sphere geometry
  39861. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39862. */
  39863. var SphereGeometry = /** @class */ (function (_super) {
  39864. __extends(SphereGeometry, _super);
  39865. /**
  39866. * Create a new sphere geometry
  39867. * @param id defines the unique ID of the geometry
  39868. * @param scene defines the hosting scene
  39869. * @param segments defines the number of segments to use to create the sphere
  39870. * @param diameter defines the diameter of the sphere
  39871. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39872. * @param mesh defines the hosting mesh (can be null)
  39873. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39874. */
  39875. function SphereGeometry(id, scene,
  39876. /**
  39877. * Defines the number of segments to use to create the sphere
  39878. */
  39879. segments,
  39880. /**
  39881. * Defines the diameter of the sphere
  39882. */
  39883. diameter, canBeRegenerated, mesh,
  39884. /**
  39885. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39886. */
  39887. side) {
  39888. if (mesh === void 0) { mesh = null; }
  39889. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39890. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39891. _this.segments = segments;
  39892. _this.diameter = diameter;
  39893. _this.side = side;
  39894. return _this;
  39895. }
  39896. SphereGeometry.prototype._regenerateVertexData = function () {
  39897. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39898. };
  39899. SphereGeometry.prototype.copy = function (id) {
  39900. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39901. };
  39902. SphereGeometry.prototype.serialize = function () {
  39903. var serializationObject = _super.prototype.serialize.call(this);
  39904. serializationObject.segments = this.segments;
  39905. serializationObject.diameter = this.diameter;
  39906. return serializationObject;
  39907. };
  39908. SphereGeometry.Parse = function (parsedSphere, scene) {
  39909. if (scene.getGeometryByID(parsedSphere.id)) {
  39910. return null; // null since geometry could be something else than a sphere...
  39911. }
  39912. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39913. if (BABYLON.Tags) {
  39914. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39915. }
  39916. scene.pushGeometry(sphere, true);
  39917. return sphere;
  39918. };
  39919. return SphereGeometry;
  39920. }(_PrimitiveGeometry));
  39921. BABYLON.SphereGeometry = SphereGeometry;
  39922. /**
  39923. * Creates a disc geometry
  39924. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39925. */
  39926. var DiscGeometry = /** @class */ (function (_super) {
  39927. __extends(DiscGeometry, _super);
  39928. /**
  39929. * Creates a new disc geometry
  39930. * @param id defines the unique ID of the geometry
  39931. * @param scene defines the hosting scene
  39932. * @param radius defines the radius of the disc
  39933. * @param tessellation defines the tesselation factor to apply to the disc
  39934. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39935. * @param mesh defines the hosting mesh (can be null)
  39936. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39937. */
  39938. function DiscGeometry(id, scene,
  39939. /**
  39940. * Defines the radius of the disc
  39941. */
  39942. radius,
  39943. /**
  39944. * Defines the tesselation factor to apply to the disc
  39945. */
  39946. tessellation, canBeRegenerated, mesh,
  39947. /**
  39948. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39949. */
  39950. side) {
  39951. if (mesh === void 0) { mesh = null; }
  39952. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39953. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39954. _this.radius = radius;
  39955. _this.tessellation = tessellation;
  39956. _this.side = side;
  39957. return _this;
  39958. }
  39959. DiscGeometry.prototype._regenerateVertexData = function () {
  39960. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39961. };
  39962. DiscGeometry.prototype.copy = function (id) {
  39963. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39964. };
  39965. return DiscGeometry;
  39966. }(_PrimitiveGeometry));
  39967. BABYLON.DiscGeometry = DiscGeometry;
  39968. /**
  39969. * Creates a new cylinder geometry
  39970. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39971. */
  39972. var CylinderGeometry = /** @class */ (function (_super) {
  39973. __extends(CylinderGeometry, _super);
  39974. /**
  39975. * Creates a new cylinder geometry
  39976. * @param id defines the unique ID of the geometry
  39977. * @param scene defines the hosting scene
  39978. * @param height defines the height of the cylinder
  39979. * @param diameterTop defines the diameter of the cylinder's top cap
  39980. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39981. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39982. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39983. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39984. * @param mesh defines the hosting mesh (can be null)
  39985. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39986. */
  39987. function CylinderGeometry(id, scene,
  39988. /**
  39989. * Defines the height of the cylinder
  39990. */
  39991. height,
  39992. /**
  39993. * Defines the diameter of the cylinder's top cap
  39994. */
  39995. diameterTop,
  39996. /**
  39997. * Defines the diameter of the cylinder's bottom cap
  39998. */
  39999. diameterBottom,
  40000. /**
  40001. * Defines the tessellation factor to apply to the cylinder
  40002. */
  40003. tessellation,
  40004. /**
  40005. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40006. */
  40007. subdivisions, canBeRegenerated, mesh,
  40008. /**
  40009. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40010. */
  40011. side) {
  40012. if (subdivisions === void 0) { subdivisions = 1; }
  40013. if (mesh === void 0) { mesh = null; }
  40014. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40015. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40016. _this.height = height;
  40017. _this.diameterTop = diameterTop;
  40018. _this.diameterBottom = diameterBottom;
  40019. _this.tessellation = tessellation;
  40020. _this.subdivisions = subdivisions;
  40021. _this.side = side;
  40022. return _this;
  40023. }
  40024. CylinderGeometry.prototype._regenerateVertexData = function () {
  40025. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40026. };
  40027. CylinderGeometry.prototype.copy = function (id) {
  40028. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40029. };
  40030. CylinderGeometry.prototype.serialize = function () {
  40031. var serializationObject = _super.prototype.serialize.call(this);
  40032. serializationObject.height = this.height;
  40033. serializationObject.diameterTop = this.diameterTop;
  40034. serializationObject.diameterBottom = this.diameterBottom;
  40035. serializationObject.tessellation = this.tessellation;
  40036. return serializationObject;
  40037. };
  40038. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40039. if (scene.getGeometryByID(parsedCylinder.id)) {
  40040. return null; // null since geometry could be something else than a cylinder...
  40041. }
  40042. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40043. if (BABYLON.Tags) {
  40044. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40045. }
  40046. scene.pushGeometry(cylinder, true);
  40047. return cylinder;
  40048. };
  40049. return CylinderGeometry;
  40050. }(_PrimitiveGeometry));
  40051. BABYLON.CylinderGeometry = CylinderGeometry;
  40052. /**
  40053. * Creates a new torus geometry
  40054. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40055. */
  40056. var TorusGeometry = /** @class */ (function (_super) {
  40057. __extends(TorusGeometry, _super);
  40058. /**
  40059. * Creates a new torus geometry
  40060. * @param id defines the unique ID of the geometry
  40061. * @param scene defines the hosting scene
  40062. * @param diameter defines the diameter of the torus
  40063. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40064. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40065. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40066. * @param mesh defines the hosting mesh (can be null)
  40067. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40068. */
  40069. function TorusGeometry(id, scene,
  40070. /**
  40071. * Defines the diameter of the torus
  40072. */
  40073. diameter,
  40074. /**
  40075. * Defines the thickness of the torus (ie. internal diameter)
  40076. */
  40077. thickness,
  40078. /**
  40079. * Defines the tesselation factor to apply to the torus
  40080. */
  40081. tessellation, canBeRegenerated, mesh,
  40082. /**
  40083. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40084. */
  40085. side) {
  40086. if (mesh === void 0) { mesh = null; }
  40087. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40088. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40089. _this.diameter = diameter;
  40090. _this.thickness = thickness;
  40091. _this.tessellation = tessellation;
  40092. _this.side = side;
  40093. return _this;
  40094. }
  40095. TorusGeometry.prototype._regenerateVertexData = function () {
  40096. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40097. };
  40098. TorusGeometry.prototype.copy = function (id) {
  40099. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40100. };
  40101. TorusGeometry.prototype.serialize = function () {
  40102. var serializationObject = _super.prototype.serialize.call(this);
  40103. serializationObject.diameter = this.diameter;
  40104. serializationObject.thickness = this.thickness;
  40105. serializationObject.tessellation = this.tessellation;
  40106. return serializationObject;
  40107. };
  40108. TorusGeometry.Parse = function (parsedTorus, scene) {
  40109. if (scene.getGeometryByID(parsedTorus.id)) {
  40110. return null; // null since geometry could be something else than a torus...
  40111. }
  40112. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40113. if (BABYLON.Tags) {
  40114. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40115. }
  40116. scene.pushGeometry(torus, true);
  40117. return torus;
  40118. };
  40119. return TorusGeometry;
  40120. }(_PrimitiveGeometry));
  40121. BABYLON.TorusGeometry = TorusGeometry;
  40122. /**
  40123. * Creates a new ground geometry
  40124. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40125. */
  40126. var GroundGeometry = /** @class */ (function (_super) {
  40127. __extends(GroundGeometry, _super);
  40128. /**
  40129. * Creates a new ground geometry
  40130. * @param id defines the unique ID of the geometry
  40131. * @param scene defines the hosting scene
  40132. * @param width defines the width of the ground
  40133. * @param height defines the height of the ground
  40134. * @param subdivisions defines the subdivisions to apply to the ground
  40135. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40136. * @param mesh defines the hosting mesh (can be null)
  40137. */
  40138. function GroundGeometry(id, scene,
  40139. /**
  40140. * Defines the width of the ground
  40141. */
  40142. width,
  40143. /**
  40144. * Defines the height of the ground
  40145. */
  40146. height,
  40147. /**
  40148. * Defines the subdivisions to apply to the ground
  40149. */
  40150. subdivisions, canBeRegenerated, mesh) {
  40151. if (mesh === void 0) { mesh = null; }
  40152. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40153. _this.width = width;
  40154. _this.height = height;
  40155. _this.subdivisions = subdivisions;
  40156. return _this;
  40157. }
  40158. GroundGeometry.prototype._regenerateVertexData = function () {
  40159. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40160. };
  40161. GroundGeometry.prototype.copy = function (id) {
  40162. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40163. };
  40164. GroundGeometry.prototype.serialize = function () {
  40165. var serializationObject = _super.prototype.serialize.call(this);
  40166. serializationObject.width = this.width;
  40167. serializationObject.height = this.height;
  40168. serializationObject.subdivisions = this.subdivisions;
  40169. return serializationObject;
  40170. };
  40171. GroundGeometry.Parse = function (parsedGround, scene) {
  40172. if (scene.getGeometryByID(parsedGround.id)) {
  40173. return null; // null since geometry could be something else than a ground...
  40174. }
  40175. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40176. if (BABYLON.Tags) {
  40177. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40178. }
  40179. scene.pushGeometry(ground, true);
  40180. return ground;
  40181. };
  40182. return GroundGeometry;
  40183. }(_PrimitiveGeometry));
  40184. BABYLON.GroundGeometry = GroundGeometry;
  40185. /**
  40186. * Creates a tiled ground geometry
  40187. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40188. */
  40189. var TiledGroundGeometry = /** @class */ (function (_super) {
  40190. __extends(TiledGroundGeometry, _super);
  40191. /**
  40192. * Creates a tiled ground geometry
  40193. * @param id defines the unique ID of the geometry
  40194. * @param scene defines the hosting scene
  40195. * @param xmin defines the minimum value on X axis
  40196. * @param zmin defines the minimum value on Z axis
  40197. * @param xmax defines the maximum value on X axis
  40198. * @param zmax defines the maximum value on Z axis
  40199. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40200. * @param precision defines the precision to use when computing the tiles
  40201. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40202. * @param mesh defines the hosting mesh (can be null)
  40203. */
  40204. function TiledGroundGeometry(id, scene,
  40205. /**
  40206. * Defines the minimum value on X axis
  40207. */
  40208. xmin,
  40209. /**
  40210. * Defines the minimum value on Z axis
  40211. */
  40212. zmin,
  40213. /**
  40214. * Defines the maximum value on X axis
  40215. */
  40216. xmax,
  40217. /**
  40218. * Defines the maximum value on Z axis
  40219. */
  40220. zmax,
  40221. /**
  40222. * Defines the subdivisions to apply to the ground
  40223. */
  40224. subdivisions,
  40225. /**
  40226. * Defines the precision to use when computing the tiles
  40227. */
  40228. precision, canBeRegenerated, mesh) {
  40229. if (mesh === void 0) { mesh = null; }
  40230. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40231. _this.xmin = xmin;
  40232. _this.zmin = zmin;
  40233. _this.xmax = xmax;
  40234. _this.zmax = zmax;
  40235. _this.subdivisions = subdivisions;
  40236. _this.precision = precision;
  40237. return _this;
  40238. }
  40239. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40240. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40241. };
  40242. TiledGroundGeometry.prototype.copy = function (id) {
  40243. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40244. };
  40245. return TiledGroundGeometry;
  40246. }(_PrimitiveGeometry));
  40247. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40248. /**
  40249. * Creates a plane geometry
  40250. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40251. */
  40252. var PlaneGeometry = /** @class */ (function (_super) {
  40253. __extends(PlaneGeometry, _super);
  40254. /**
  40255. * Creates a plane geometry
  40256. * @param id defines the unique ID of the geometry
  40257. * @param scene defines the hosting scene
  40258. * @param size defines the size of the plane (width === height)
  40259. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40260. * @param mesh defines the hosting mesh (can be null)
  40261. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40262. */
  40263. function PlaneGeometry(id, scene,
  40264. /**
  40265. * Defines the size of the plane (width === height)
  40266. */
  40267. size, canBeRegenerated, mesh,
  40268. /**
  40269. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40270. */
  40271. side) {
  40272. if (mesh === void 0) { mesh = null; }
  40273. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40274. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40275. _this.size = size;
  40276. _this.side = side;
  40277. return _this;
  40278. }
  40279. PlaneGeometry.prototype._regenerateVertexData = function () {
  40280. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40281. };
  40282. PlaneGeometry.prototype.copy = function (id) {
  40283. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40284. };
  40285. PlaneGeometry.prototype.serialize = function () {
  40286. var serializationObject = _super.prototype.serialize.call(this);
  40287. serializationObject.size = this.size;
  40288. return serializationObject;
  40289. };
  40290. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40291. if (scene.getGeometryByID(parsedPlane.id)) {
  40292. return null; // null since geometry could be something else than a ground...
  40293. }
  40294. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40295. if (BABYLON.Tags) {
  40296. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40297. }
  40298. scene.pushGeometry(plane, true);
  40299. return plane;
  40300. };
  40301. return PlaneGeometry;
  40302. }(_PrimitiveGeometry));
  40303. BABYLON.PlaneGeometry = PlaneGeometry;
  40304. /**
  40305. * Creates a torus knot geometry
  40306. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40307. */
  40308. var TorusKnotGeometry = /** @class */ (function (_super) {
  40309. __extends(TorusKnotGeometry, _super);
  40310. /**
  40311. * Creates a torus knot geometry
  40312. * @param id defines the unique ID of the geometry
  40313. * @param scene defines the hosting scene
  40314. * @param radius defines the radius of the torus knot
  40315. * @param tube defines the thickness of the torus knot tube
  40316. * @param radialSegments defines the number of radial segments
  40317. * @param tubularSegments defines the number of tubular segments
  40318. * @param p defines the first number of windings
  40319. * @param q defines the second number of windings
  40320. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40321. * @param mesh defines the hosting mesh (can be null)
  40322. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40323. */
  40324. function TorusKnotGeometry(id, scene,
  40325. /**
  40326. * Defines the radius of the torus knot
  40327. */
  40328. radius,
  40329. /**
  40330. * Defines the thickness of the torus knot tube
  40331. */
  40332. tube,
  40333. /**
  40334. * Defines the number of radial segments
  40335. */
  40336. radialSegments,
  40337. /**
  40338. * Defines the number of tubular segments
  40339. */
  40340. tubularSegments,
  40341. /**
  40342. * Defines the first number of windings
  40343. */
  40344. p,
  40345. /**
  40346. * Defines the second number of windings
  40347. */
  40348. q, canBeRegenerated, mesh,
  40349. /**
  40350. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40351. */
  40352. side) {
  40353. if (mesh === void 0) { mesh = null; }
  40354. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40355. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40356. _this.radius = radius;
  40357. _this.tube = tube;
  40358. _this.radialSegments = radialSegments;
  40359. _this.tubularSegments = tubularSegments;
  40360. _this.p = p;
  40361. _this.q = q;
  40362. _this.side = side;
  40363. return _this;
  40364. }
  40365. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40366. 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 });
  40367. };
  40368. TorusKnotGeometry.prototype.copy = function (id) {
  40369. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40370. };
  40371. TorusKnotGeometry.prototype.serialize = function () {
  40372. var serializationObject = _super.prototype.serialize.call(this);
  40373. serializationObject.radius = this.radius;
  40374. serializationObject.tube = this.tube;
  40375. serializationObject.radialSegments = this.radialSegments;
  40376. serializationObject.tubularSegments = this.tubularSegments;
  40377. serializationObject.p = this.p;
  40378. serializationObject.q = this.q;
  40379. return serializationObject;
  40380. };
  40381. ;
  40382. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40383. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40384. return null; // null since geometry could be something else than a ground...
  40385. }
  40386. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40387. if (BABYLON.Tags) {
  40388. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40389. }
  40390. scene.pushGeometry(torusKnot, true);
  40391. return torusKnot;
  40392. };
  40393. return TorusKnotGeometry;
  40394. }(_PrimitiveGeometry));
  40395. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40396. //}
  40397. })(BABYLON || (BABYLON = {}));
  40398. //# sourceMappingURL=babylon.geometry.js.map
  40399. var BABYLON;
  40400. (function (BABYLON) {
  40401. /**
  40402. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40403. */
  40404. var PerformanceMonitor = /** @class */ (function () {
  40405. /**
  40406. * constructor
  40407. * @param frameSampleSize The number of samples required to saturate the sliding window
  40408. */
  40409. function PerformanceMonitor(frameSampleSize) {
  40410. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40411. this._enabled = true;
  40412. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40413. }
  40414. /**
  40415. * Samples current frame
  40416. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40417. */
  40418. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40419. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40420. if (!this._enabled)
  40421. return;
  40422. if (this._lastFrameTimeMs != null) {
  40423. var dt = timeMs - this._lastFrameTimeMs;
  40424. this._rollingFrameTime.add(dt);
  40425. }
  40426. this._lastFrameTimeMs = timeMs;
  40427. };
  40428. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40429. /**
  40430. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40431. * @return Average frame time in milliseconds
  40432. */
  40433. get: function () {
  40434. return this._rollingFrameTime.average;
  40435. },
  40436. enumerable: true,
  40437. configurable: true
  40438. });
  40439. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40440. /**
  40441. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40442. * @return Frame time variance in milliseconds squared
  40443. */
  40444. get: function () {
  40445. return this._rollingFrameTime.variance;
  40446. },
  40447. enumerable: true,
  40448. configurable: true
  40449. });
  40450. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40451. /**
  40452. * Returns the frame time of the most recent frame
  40453. * @return Frame time in milliseconds
  40454. */
  40455. get: function () {
  40456. return this._rollingFrameTime.history(0);
  40457. },
  40458. enumerable: true,
  40459. configurable: true
  40460. });
  40461. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40462. /**
  40463. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40464. * @return Framerate in frames per second
  40465. */
  40466. get: function () {
  40467. return 1000.0 / this._rollingFrameTime.average;
  40468. },
  40469. enumerable: true,
  40470. configurable: true
  40471. });
  40472. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40473. /**
  40474. * Returns the average framerate in frames per second using the most recent frame time
  40475. * @return Framerate in frames per second
  40476. */
  40477. get: function () {
  40478. var history = this._rollingFrameTime.history(0);
  40479. if (history === 0) {
  40480. return 0;
  40481. }
  40482. return 1000.0 / history;
  40483. },
  40484. enumerable: true,
  40485. configurable: true
  40486. });
  40487. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40488. /**
  40489. * Returns true if enough samples have been taken to completely fill the sliding window
  40490. * @return true if saturated
  40491. */
  40492. get: function () {
  40493. return this._rollingFrameTime.isSaturated();
  40494. },
  40495. enumerable: true,
  40496. configurable: true
  40497. });
  40498. /**
  40499. * Enables contributions to the sliding window sample set
  40500. */
  40501. PerformanceMonitor.prototype.enable = function () {
  40502. this._enabled = true;
  40503. };
  40504. /**
  40505. * Disables contributions to the sliding window sample set
  40506. * Samples will not be interpolated over the disabled period
  40507. */
  40508. PerformanceMonitor.prototype.disable = function () {
  40509. this._enabled = false;
  40510. //clear last sample to avoid interpolating over the disabled period when next enabled
  40511. this._lastFrameTimeMs = null;
  40512. };
  40513. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40514. /**
  40515. * Returns true if sampling is enabled
  40516. * @return true if enabled
  40517. */
  40518. get: function () {
  40519. return this._enabled;
  40520. },
  40521. enumerable: true,
  40522. configurable: true
  40523. });
  40524. /**
  40525. * Resets performance monitor
  40526. */
  40527. PerformanceMonitor.prototype.reset = function () {
  40528. //clear last sample to avoid interpolating over the disabled period when next enabled
  40529. this._lastFrameTimeMs = null;
  40530. //wipe record
  40531. this._rollingFrameTime.reset();
  40532. };
  40533. return PerformanceMonitor;
  40534. }());
  40535. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40536. /**
  40537. * RollingAverage
  40538. *
  40539. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40540. */
  40541. var RollingAverage = /** @class */ (function () {
  40542. /**
  40543. * constructor
  40544. * @param length The number of samples required to saturate the sliding window
  40545. */
  40546. function RollingAverage(length) {
  40547. this._samples = new Array(length);
  40548. this.reset();
  40549. }
  40550. /**
  40551. * Adds a sample to the sample set
  40552. * @param v The sample value
  40553. */
  40554. RollingAverage.prototype.add = function (v) {
  40555. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40556. var delta;
  40557. //we need to check if we've already wrapped round
  40558. if (this.isSaturated()) {
  40559. //remove bottom of stack from mean
  40560. var bottomValue = this._samples[this._pos];
  40561. delta = bottomValue - this.average;
  40562. this.average -= delta / (this._sampleCount - 1);
  40563. this._m2 -= delta * (bottomValue - this.average);
  40564. }
  40565. else {
  40566. this._sampleCount++;
  40567. }
  40568. //add new value to mean
  40569. delta = v - this.average;
  40570. this.average += delta / (this._sampleCount);
  40571. this._m2 += delta * (v - this.average);
  40572. //set the new variance
  40573. this.variance = this._m2 / (this._sampleCount - 1);
  40574. this._samples[this._pos] = v;
  40575. this._pos++;
  40576. this._pos %= this._samples.length; //positive wrap around
  40577. };
  40578. /**
  40579. * Returns previously added values or null if outside of history or outside the sliding window domain
  40580. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40581. * @return Value previously recorded with add() or null if outside of range
  40582. */
  40583. RollingAverage.prototype.history = function (i) {
  40584. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40585. return 0;
  40586. }
  40587. var i0 = this._wrapPosition(this._pos - 1.0);
  40588. return this._samples[this._wrapPosition(i0 - i)];
  40589. };
  40590. /**
  40591. * Returns true if enough samples have been taken to completely fill the sliding window
  40592. * @return true if sample-set saturated
  40593. */
  40594. RollingAverage.prototype.isSaturated = function () {
  40595. return this._sampleCount >= this._samples.length;
  40596. };
  40597. /**
  40598. * Resets the rolling average (equivalent to 0 samples taken so far)
  40599. */
  40600. RollingAverage.prototype.reset = function () {
  40601. this.average = 0;
  40602. this.variance = 0;
  40603. this._sampleCount = 0;
  40604. this._pos = 0;
  40605. this._m2 = 0;
  40606. };
  40607. /**
  40608. * Wraps a value around the sample range boundaries
  40609. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40610. * @return Wrapped position in sample range
  40611. */
  40612. RollingAverage.prototype._wrapPosition = function (i) {
  40613. var max = this._samples.length;
  40614. return ((i % max) + max) % max;
  40615. };
  40616. return RollingAverage;
  40617. }());
  40618. BABYLON.RollingAverage = RollingAverage;
  40619. })(BABYLON || (BABYLON = {}));
  40620. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40621. var BABYLON;
  40622. (function (BABYLON) {
  40623. /**
  40624. * "Static Class" containing the most commonly used helper while dealing with material for
  40625. * rendering purpose.
  40626. *
  40627. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40628. *
  40629. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40630. */
  40631. var MaterialHelper = /** @class */ (function () {
  40632. function MaterialHelper() {
  40633. }
  40634. /**
  40635. * Bind the current view position to an effect.
  40636. * @param effect The effect to be bound
  40637. * @param scene The scene the eyes position is used from
  40638. */
  40639. MaterialHelper.BindEyePosition = function (effect, scene) {
  40640. if (scene._forcedViewPosition) {
  40641. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40642. return;
  40643. }
  40644. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40645. };
  40646. /**
  40647. * Helps preparing the defines values about the UVs in used in the effect.
  40648. * UVs are shared as much as we can accross chanels in the shaders.
  40649. * @param texture The texture we are preparing the UVs for
  40650. * @param defines The defines to update
  40651. * @param key The chanel key "diffuse", "specular"... used in the shader
  40652. */
  40653. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40654. defines._needUVs = true;
  40655. defines[key] = true;
  40656. if (texture.getTextureMatrix().isIdentity(true)) {
  40657. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40658. if (texture.coordinatesIndex === 0) {
  40659. defines["MAINUV1"] = true;
  40660. }
  40661. else {
  40662. defines["MAINUV2"] = true;
  40663. }
  40664. }
  40665. else {
  40666. defines[key + "DIRECTUV"] = 0;
  40667. }
  40668. };
  40669. /**
  40670. * Binds a texture matrix value to its corrsponding uniform
  40671. * @param texture The texture to bind the matrix for
  40672. * @param uniformBuffer The uniform buffer receivin the data
  40673. * @param key The chanel key "diffuse", "specular"... used in the shader
  40674. */
  40675. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40676. var matrix = texture.getTextureMatrix();
  40677. if (!matrix.isIdentity(true)) {
  40678. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40679. }
  40680. };
  40681. /**
  40682. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40683. * @param mesh defines the current mesh
  40684. * @param scene defines the current scene
  40685. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40686. * @param pointsCloud defines if point cloud rendering has to be turned on
  40687. * @param fogEnabled defines if fog has to be turned on
  40688. * @param alphaTest defines if alpha testing has to be turned on
  40689. * @param defines defines the current list of defines
  40690. */
  40691. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40692. if (defines._areMiscDirty) {
  40693. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40694. defines["POINTSIZE"] = pointsCloud;
  40695. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40696. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40697. defines["ALPHATEST"] = alphaTest;
  40698. }
  40699. };
  40700. /**
  40701. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40702. * @param scene defines the current scene
  40703. * @param engine defines the current engine
  40704. * @param defines specifies the list of active defines
  40705. * @param useInstances defines if instances have to be turned on
  40706. * @param useClipPlane defines if clip plane have to be turned on
  40707. */
  40708. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40709. if (useClipPlane === void 0) { useClipPlane = null; }
  40710. var changed = false;
  40711. if (useClipPlane == null) {
  40712. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40713. }
  40714. if (defines["CLIPPLANE"] !== useClipPlane) {
  40715. defines["CLIPPLANE"] = useClipPlane;
  40716. changed = true;
  40717. }
  40718. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40719. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40720. changed = true;
  40721. }
  40722. if (defines["INSTANCES"] !== useInstances) {
  40723. defines["INSTANCES"] = useInstances;
  40724. changed = true;
  40725. }
  40726. if (changed) {
  40727. defines.markAsUnprocessed();
  40728. }
  40729. };
  40730. /**
  40731. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40732. * @param mesh The mesh containing the geometry data we will draw
  40733. * @param defines The defines to update
  40734. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40735. * @param useBones Precise whether bones should be used or not (override mesh info)
  40736. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40737. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40738. * @returns false if defines are considered not dirty and have not been checked
  40739. */
  40740. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40741. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40742. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40743. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40744. return false;
  40745. }
  40746. defines._normals = defines._needNormals;
  40747. defines._uvs = defines._needUVs;
  40748. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40749. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40750. defines["TANGENT"] = true;
  40751. }
  40752. if (defines._needUVs) {
  40753. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40754. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40755. }
  40756. else {
  40757. defines["UV1"] = false;
  40758. defines["UV2"] = false;
  40759. }
  40760. if (useVertexColor) {
  40761. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40762. defines["VERTEXCOLOR"] = hasVertexColors;
  40763. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40764. }
  40765. if (useBones) {
  40766. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40767. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40768. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40769. }
  40770. else {
  40771. defines["NUM_BONE_INFLUENCERS"] = 0;
  40772. defines["BonesPerMesh"] = 0;
  40773. }
  40774. }
  40775. if (useMorphTargets) {
  40776. var manager = mesh.morphTargetManager;
  40777. if (manager) {
  40778. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40779. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40780. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40781. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40782. }
  40783. else {
  40784. defines["MORPHTARGETS_TANGENT"] = false;
  40785. defines["MORPHTARGETS_NORMAL"] = false;
  40786. defines["MORPHTARGETS"] = false;
  40787. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40788. }
  40789. }
  40790. return true;
  40791. };
  40792. /**
  40793. * Prepares the defines related to the light information passed in parameter
  40794. * @param scene The scene we are intending to draw
  40795. * @param mesh The mesh the effect is compiling for
  40796. * @param defines The defines to update
  40797. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40798. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40799. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40800. * @returns true if normals will be required for the rest of the effect
  40801. */
  40802. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40803. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40804. if (disableLighting === void 0) { disableLighting = false; }
  40805. if (!defines._areLightsDirty) {
  40806. return defines._needNormals;
  40807. }
  40808. var lightIndex = 0;
  40809. var needNormals = false;
  40810. var needRebuild = false;
  40811. var lightmapMode = false;
  40812. var shadowEnabled = false;
  40813. var specularEnabled = false;
  40814. if (scene.lightsEnabled && !disableLighting) {
  40815. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40816. var light = _a[_i];
  40817. needNormals = true;
  40818. if (defines["LIGHT" + lightIndex] === undefined) {
  40819. needRebuild = true;
  40820. }
  40821. defines["LIGHT" + lightIndex] = true;
  40822. defines["SPOTLIGHT" + lightIndex] = false;
  40823. defines["HEMILIGHT" + lightIndex] = false;
  40824. defines["POINTLIGHT" + lightIndex] = false;
  40825. defines["DIRLIGHT" + lightIndex] = false;
  40826. light.prepareLightSpecificDefines(defines, lightIndex);
  40827. // Specular
  40828. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40829. specularEnabled = true;
  40830. }
  40831. // Shadows
  40832. defines["SHADOW" + lightIndex] = false;
  40833. defines["SHADOWPCF" + lightIndex] = false;
  40834. defines["SHADOWPCSS" + lightIndex] = false;
  40835. defines["SHADOWPOISSON" + lightIndex] = false;
  40836. defines["SHADOWESM" + lightIndex] = false;
  40837. defines["SHADOWCUBE" + lightIndex] = false;
  40838. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40839. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40840. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40841. var shadowGenerator = light.getShadowGenerator();
  40842. if (shadowGenerator) {
  40843. var shadowMap = shadowGenerator.getShadowMap();
  40844. if (shadowMap) {
  40845. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40846. shadowEnabled = true;
  40847. shadowGenerator.prepareDefines(defines, lightIndex);
  40848. }
  40849. }
  40850. }
  40851. }
  40852. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40853. lightmapMode = true;
  40854. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40855. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40856. }
  40857. else {
  40858. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40859. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40860. }
  40861. lightIndex++;
  40862. if (lightIndex === maxSimultaneousLights)
  40863. break;
  40864. }
  40865. }
  40866. defines["SPECULARTERM"] = specularEnabled;
  40867. defines["SHADOWS"] = shadowEnabled;
  40868. // Resetting all other lights if any
  40869. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40870. if (defines["LIGHT" + index] !== undefined) {
  40871. defines["LIGHT" + index] = false;
  40872. defines["HEMILIGHT" + lightIndex] = false;
  40873. defines["POINTLIGHT" + lightIndex] = false;
  40874. defines["DIRLIGHT" + lightIndex] = false;
  40875. defines["SPOTLIGHT" + lightIndex] = false;
  40876. defines["SHADOW" + lightIndex] = false;
  40877. }
  40878. }
  40879. var caps = scene.getEngine().getCaps();
  40880. if (defines["SHADOWFLOAT"] === undefined) {
  40881. needRebuild = true;
  40882. }
  40883. defines["SHADOWFLOAT"] = shadowEnabled &&
  40884. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40885. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40886. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40887. if (needRebuild) {
  40888. defines.rebuild();
  40889. }
  40890. return needNormals;
  40891. };
  40892. /**
  40893. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40894. * that won t be acctive due to defines being turned off.
  40895. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40896. * @param samplersList The samplers list
  40897. * @param defines The defines helping in the list generation
  40898. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40899. */
  40900. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40901. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40902. var uniformsList;
  40903. var uniformBuffersList = null;
  40904. if (uniformsListOrOptions.uniformsNames) {
  40905. var options = uniformsListOrOptions;
  40906. uniformsList = options.uniformsNames;
  40907. uniformBuffersList = options.uniformBuffersNames;
  40908. samplersList = options.samplers;
  40909. defines = options.defines;
  40910. maxSimultaneousLights = options.maxSimultaneousLights;
  40911. }
  40912. else {
  40913. uniformsList = uniformsListOrOptions;
  40914. if (!samplersList) {
  40915. samplersList = [];
  40916. }
  40917. }
  40918. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40919. if (!defines["LIGHT" + lightIndex]) {
  40920. break;
  40921. }
  40922. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40923. if (uniformBuffersList) {
  40924. uniformBuffersList.push("Light" + lightIndex);
  40925. }
  40926. samplersList.push("shadowSampler" + lightIndex);
  40927. samplersList.push("depthSampler" + lightIndex);
  40928. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40929. samplersList.push("projectionLightSampler" + lightIndex);
  40930. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40931. }
  40932. }
  40933. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40934. uniformsList.push("morphTargetInfluences");
  40935. }
  40936. };
  40937. /**
  40938. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40939. * @param defines The defines to update while falling back
  40940. * @param fallbacks The authorized effect fallbacks
  40941. * @param maxSimultaneousLights The maximum number of lights allowed
  40942. * @param rank the current rank of the Effect
  40943. * @returns The newly affected rank
  40944. */
  40945. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40946. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40947. if (rank === void 0) { rank = 0; }
  40948. var lightFallbackRank = 0;
  40949. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40950. if (!defines["LIGHT" + lightIndex]) {
  40951. break;
  40952. }
  40953. if (lightIndex > 0) {
  40954. lightFallbackRank = rank + lightIndex;
  40955. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40956. }
  40957. if (!defines["SHADOWS"]) {
  40958. if (defines["SHADOW" + lightIndex]) {
  40959. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40960. }
  40961. if (defines["SHADOWPCF" + lightIndex]) {
  40962. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40963. }
  40964. if (defines["SHADOWPCSS" + lightIndex]) {
  40965. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40966. }
  40967. if (defines["SHADOWPOISSON" + lightIndex]) {
  40968. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40969. }
  40970. if (defines["SHADOWESM" + lightIndex]) {
  40971. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40972. }
  40973. }
  40974. }
  40975. return lightFallbackRank++;
  40976. };
  40977. /**
  40978. * Prepares the list of attributes required for morph targets according to the effect defines.
  40979. * @param attribs The current list of supported attribs
  40980. * @param mesh The mesh to prepare the morph targets attributes for
  40981. * @param defines The current Defines of the effect
  40982. */
  40983. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40984. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40985. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40986. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40987. var manager = mesh.morphTargetManager;
  40988. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40989. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40990. for (var index = 0; index < influencers; index++) {
  40991. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40992. if (normal) {
  40993. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40994. }
  40995. if (tangent) {
  40996. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40997. }
  40998. if (attribs.length > maxAttributesCount) {
  40999. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41000. }
  41001. }
  41002. }
  41003. };
  41004. /**
  41005. * Prepares the list of attributes required for bones according to the effect defines.
  41006. * @param attribs The current list of supported attribs
  41007. * @param mesh The mesh to prepare the bones attributes for
  41008. * @param defines The current Defines of the effect
  41009. * @param fallbacks The current efffect fallback strategy
  41010. */
  41011. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41012. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41013. fallbacks.addCPUSkinningFallback(0, mesh);
  41014. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41015. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41016. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41017. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41018. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41019. }
  41020. }
  41021. };
  41022. /**
  41023. * Prepares the list of attributes required for instances according to the effect defines.
  41024. * @param attribs The current list of supported attribs
  41025. * @param defines The current Defines of the effect
  41026. */
  41027. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41028. if (defines["INSTANCES"]) {
  41029. attribs.push("world0");
  41030. attribs.push("world1");
  41031. attribs.push("world2");
  41032. attribs.push("world3");
  41033. }
  41034. };
  41035. /**
  41036. * Binds the light shadow information to the effect for the given mesh.
  41037. * @param light The light containing the generator
  41038. * @param scene The scene the lights belongs to
  41039. * @param mesh The mesh we are binding the information to render
  41040. * @param lightIndex The light index in the effect used to render the mesh
  41041. * @param effect The effect we are binding the data to
  41042. */
  41043. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41044. if (light.shadowEnabled && mesh.receiveShadows) {
  41045. var shadowGenerator = light.getShadowGenerator();
  41046. if (shadowGenerator) {
  41047. shadowGenerator.bindShadowLight(lightIndex, effect);
  41048. }
  41049. }
  41050. };
  41051. /**
  41052. * Binds the light information to the effect.
  41053. * @param light The light containing the generator
  41054. * @param effect The effect we are binding the data to
  41055. * @param lightIndex The light index in the effect used to render
  41056. */
  41057. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41058. light.transferToEffect(effect, lightIndex + "");
  41059. };
  41060. /**
  41061. * Binds the lights information from the scene to the effect for the given mesh.
  41062. * @param scene The scene the lights belongs to
  41063. * @param mesh The mesh we are binding the information to render
  41064. * @param effect The effect we are binding the data to
  41065. * @param defines The generated defines for the effect
  41066. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41067. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41068. */
  41069. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41070. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41071. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41072. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41073. for (var i = 0; i < len; i++) {
  41074. var light = mesh._lightSources[i];
  41075. var iAsString = i.toString();
  41076. var scaledIntensity = light.getScaledIntensity();
  41077. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41078. MaterialHelper.BindLightProperties(light, effect, i);
  41079. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41080. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41081. if (defines["SPECULARTERM"]) {
  41082. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41083. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41084. }
  41085. // Shadows
  41086. if (scene.shadowsEnabled) {
  41087. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41088. }
  41089. light._uniformBuffer.update();
  41090. }
  41091. };
  41092. /**
  41093. * Binds the fog information from the scene to the effect for the given mesh.
  41094. * @param scene The scene the lights belongs to
  41095. * @param mesh The mesh we are binding the information to render
  41096. * @param effect The effect we are binding the data to
  41097. */
  41098. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41099. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41100. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41101. effect.setColor3("vFogColor", scene.fogColor);
  41102. }
  41103. };
  41104. /**
  41105. * Binds the bones information from the mesh to the effect.
  41106. * @param mesh The mesh we are binding the information to render
  41107. * @param effect The effect we are binding the data to
  41108. */
  41109. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41110. if (!effect || !mesh) {
  41111. return;
  41112. }
  41113. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41114. mesh.computeBonesUsingShaders = false;
  41115. }
  41116. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41117. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41118. if (matrices) {
  41119. effect.setMatrices("mBones", matrices);
  41120. }
  41121. }
  41122. };
  41123. /**
  41124. * Binds the morph targets information from the mesh to the effect.
  41125. * @param abstractMesh The mesh we are binding the information to render
  41126. * @param effect The effect we are binding the data to
  41127. */
  41128. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41129. var manager = abstractMesh.morphTargetManager;
  41130. if (!abstractMesh || !manager) {
  41131. return;
  41132. }
  41133. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41134. };
  41135. /**
  41136. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41137. * @param defines The generated defines used in the effect
  41138. * @param effect The effect we are binding the data to
  41139. * @param scene The scene we are willing to render with logarithmic scale for
  41140. */
  41141. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41142. if (defines["LOGARITHMICDEPTH"]) {
  41143. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41144. }
  41145. };
  41146. /**
  41147. * Binds the clip plane information from the scene to the effect.
  41148. * @param scene The scene the clip plane information are extracted from
  41149. * @param effect The effect we are binding the data to
  41150. */
  41151. MaterialHelper.BindClipPlane = function (effect, scene) {
  41152. if (scene.clipPlane) {
  41153. var clipPlane = scene.clipPlane;
  41154. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41155. }
  41156. };
  41157. return MaterialHelper;
  41158. }());
  41159. BABYLON.MaterialHelper = MaterialHelper;
  41160. })(BABYLON || (BABYLON = {}));
  41161. //# sourceMappingURL=babylon.materialHelper.js.map
  41162. var BABYLON;
  41163. (function (BABYLON) {
  41164. var PushMaterial = /** @class */ (function (_super) {
  41165. __extends(PushMaterial, _super);
  41166. function PushMaterial(name, scene) {
  41167. var _this = _super.call(this, name, scene) || this;
  41168. _this._normalMatrix = new BABYLON.Matrix();
  41169. _this.storeEffectOnSubMeshes = true;
  41170. return _this;
  41171. }
  41172. PushMaterial.prototype.getEffect = function () {
  41173. return this._activeEffect;
  41174. };
  41175. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41176. if (!mesh) {
  41177. return false;
  41178. }
  41179. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41180. return true;
  41181. }
  41182. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41183. };
  41184. /**
  41185. * Binds the given world matrix to the active effect
  41186. *
  41187. * @param world the matrix to bind
  41188. */
  41189. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41190. this._activeEffect.setMatrix("world", world);
  41191. };
  41192. /**
  41193. * Binds the given normal matrix to the active effect
  41194. *
  41195. * @param normalMatrix the matrix to bind
  41196. */
  41197. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41198. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41199. };
  41200. PushMaterial.prototype.bind = function (world, mesh) {
  41201. if (!mesh) {
  41202. return;
  41203. }
  41204. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41205. };
  41206. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41207. if (effect === void 0) { effect = null; }
  41208. _super.prototype._afterBind.call(this, mesh);
  41209. this.getScene()._cachedEffect = effect;
  41210. };
  41211. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41212. if (visibility === void 0) { visibility = 1; }
  41213. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41214. };
  41215. return PushMaterial;
  41216. }(BABYLON.Material));
  41217. BABYLON.PushMaterial = PushMaterial;
  41218. })(BABYLON || (BABYLON = {}));
  41219. //# sourceMappingURL=babylon.pushMaterial.js.map
  41220. var BABYLON;
  41221. (function (BABYLON) {
  41222. /** @hidden */
  41223. var StandardMaterialDefines = /** @class */ (function (_super) {
  41224. __extends(StandardMaterialDefines, _super);
  41225. function StandardMaterialDefines() {
  41226. var _this = _super.call(this) || this;
  41227. _this.MAINUV1 = false;
  41228. _this.MAINUV2 = false;
  41229. _this.DIFFUSE = false;
  41230. _this.DIFFUSEDIRECTUV = 0;
  41231. _this.AMBIENT = false;
  41232. _this.AMBIENTDIRECTUV = 0;
  41233. _this.OPACITY = false;
  41234. _this.OPACITYDIRECTUV = 0;
  41235. _this.OPACITYRGB = false;
  41236. _this.REFLECTION = false;
  41237. _this.EMISSIVE = false;
  41238. _this.EMISSIVEDIRECTUV = 0;
  41239. _this.SPECULAR = false;
  41240. _this.SPECULARDIRECTUV = 0;
  41241. _this.BUMP = false;
  41242. _this.BUMPDIRECTUV = 0;
  41243. _this.PARALLAX = false;
  41244. _this.PARALLAXOCCLUSION = false;
  41245. _this.SPECULAROVERALPHA = false;
  41246. _this.CLIPPLANE = false;
  41247. _this.ALPHATEST = false;
  41248. _this.DEPTHPREPASS = false;
  41249. _this.ALPHAFROMDIFFUSE = false;
  41250. _this.POINTSIZE = false;
  41251. _this.FOG = false;
  41252. _this.SPECULARTERM = false;
  41253. _this.DIFFUSEFRESNEL = false;
  41254. _this.OPACITYFRESNEL = false;
  41255. _this.REFLECTIONFRESNEL = false;
  41256. _this.REFRACTIONFRESNEL = false;
  41257. _this.EMISSIVEFRESNEL = false;
  41258. _this.FRESNEL = false;
  41259. _this.NORMAL = false;
  41260. _this.UV1 = false;
  41261. _this.UV2 = false;
  41262. _this.VERTEXCOLOR = false;
  41263. _this.VERTEXALPHA = false;
  41264. _this.NUM_BONE_INFLUENCERS = 0;
  41265. _this.BonesPerMesh = 0;
  41266. _this.INSTANCES = false;
  41267. _this.GLOSSINESS = false;
  41268. _this.ROUGHNESS = false;
  41269. _this.EMISSIVEASILLUMINATION = false;
  41270. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41271. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41272. _this.LIGHTMAP = false;
  41273. _this.LIGHTMAPDIRECTUV = 0;
  41274. _this.OBJECTSPACE_NORMALMAP = false;
  41275. _this.USELIGHTMAPASSHADOWMAP = false;
  41276. _this.REFLECTIONMAP_3D = false;
  41277. _this.REFLECTIONMAP_SPHERICAL = false;
  41278. _this.REFLECTIONMAP_PLANAR = false;
  41279. _this.REFLECTIONMAP_CUBIC = false;
  41280. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41281. _this.REFLECTIONMAP_PROJECTION = false;
  41282. _this.REFLECTIONMAP_SKYBOX = false;
  41283. _this.REFLECTIONMAP_EXPLICIT = false;
  41284. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41285. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41286. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41287. _this.INVERTCUBICMAP = false;
  41288. _this.LOGARITHMICDEPTH = false;
  41289. _this.REFRACTION = false;
  41290. _this.REFRACTIONMAP_3D = false;
  41291. _this.REFLECTIONOVERALPHA = false;
  41292. _this.TWOSIDEDLIGHTING = false;
  41293. _this.SHADOWFLOAT = false;
  41294. _this.MORPHTARGETS = false;
  41295. _this.MORPHTARGETS_NORMAL = false;
  41296. _this.MORPHTARGETS_TANGENT = false;
  41297. _this.NUM_MORPH_INFLUENCERS = 0;
  41298. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41299. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41300. _this.IMAGEPROCESSING = false;
  41301. _this.VIGNETTE = false;
  41302. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41303. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41304. _this.TONEMAPPING = false;
  41305. _this.CONTRAST = false;
  41306. _this.COLORCURVES = false;
  41307. _this.COLORGRADING = false;
  41308. _this.COLORGRADING3D = false;
  41309. _this.SAMPLER3DGREENDEPTH = false;
  41310. _this.SAMPLER3DBGRMAP = false;
  41311. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41312. /**
  41313. * If the reflection texture on this material is in linear color space
  41314. * @hidden
  41315. */
  41316. _this.IS_REFLECTION_LINEAR = false;
  41317. /**
  41318. * If the refraction texture on this material is in linear color space
  41319. * @hidden
  41320. */
  41321. _this.IS_REFRACTION_LINEAR = false;
  41322. _this.EXPOSURE = false;
  41323. _this.rebuild();
  41324. return _this;
  41325. }
  41326. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41327. var modes = [
  41328. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41329. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41330. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41331. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41332. ];
  41333. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41334. var mode = modes_1[_i];
  41335. this[mode] = (mode === modeToEnable);
  41336. }
  41337. };
  41338. return StandardMaterialDefines;
  41339. }(BABYLON.MaterialDefines));
  41340. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41341. var StandardMaterial = /** @class */ (function (_super) {
  41342. __extends(StandardMaterial, _super);
  41343. function StandardMaterial(name, scene) {
  41344. var _this = _super.call(this, name, scene) || this;
  41345. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41346. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41347. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41348. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41349. _this.specularPower = 64;
  41350. _this._useAlphaFromDiffuseTexture = false;
  41351. _this._useEmissiveAsIllumination = false;
  41352. _this._linkEmissiveWithDiffuse = false;
  41353. _this._useSpecularOverAlpha = false;
  41354. _this._useReflectionOverAlpha = false;
  41355. _this._disableLighting = false;
  41356. _this._useObjectSpaceNormalMap = false;
  41357. _this._useParallax = false;
  41358. _this._useParallaxOcclusion = false;
  41359. _this.parallaxScaleBias = 0.05;
  41360. _this._roughness = 0;
  41361. _this.indexOfRefraction = 0.98;
  41362. _this.invertRefractionY = true;
  41363. /**
  41364. * Defines the alpha limits in alpha test mode
  41365. */
  41366. _this.alphaCutOff = 0.4;
  41367. _this._useLightmapAsShadowmap = false;
  41368. _this._useReflectionFresnelFromSpecular = false;
  41369. _this._useGlossinessFromSpecularMapAlpha = false;
  41370. _this._maxSimultaneousLights = 4;
  41371. /**
  41372. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41373. */
  41374. _this._invertNormalMapX = false;
  41375. /**
  41376. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41377. */
  41378. _this._invertNormalMapY = false;
  41379. /**
  41380. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41381. */
  41382. _this._twoSidedLighting = false;
  41383. _this._renderTargets = new BABYLON.SmartArray(16);
  41384. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41385. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41386. // Setup the default processing configuration to the scene.
  41387. _this._attachImageProcessingConfiguration(null);
  41388. _this.getRenderTargetTextures = function () {
  41389. _this._renderTargets.reset();
  41390. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41391. _this._renderTargets.push(_this._reflectionTexture);
  41392. }
  41393. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41394. _this._renderTargets.push(_this._refractionTexture);
  41395. }
  41396. return _this._renderTargets;
  41397. };
  41398. return _this;
  41399. }
  41400. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41401. /**
  41402. * Gets the image processing configuration used either in this material.
  41403. */
  41404. get: function () {
  41405. return this._imageProcessingConfiguration;
  41406. },
  41407. /**
  41408. * Sets the Default image processing configuration used either in the this material.
  41409. *
  41410. * If sets to null, the scene one is in use.
  41411. */
  41412. set: function (value) {
  41413. this._attachImageProcessingConfiguration(value);
  41414. // Ensure the effect will be rebuilt.
  41415. this._markAllSubMeshesAsTexturesDirty();
  41416. },
  41417. enumerable: true,
  41418. configurable: true
  41419. });
  41420. /**
  41421. * Attaches a new image processing configuration to the Standard Material.
  41422. * @param configuration
  41423. */
  41424. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41425. var _this = this;
  41426. if (configuration === this._imageProcessingConfiguration) {
  41427. return;
  41428. }
  41429. // Detaches observer.
  41430. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41431. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41432. }
  41433. // Pick the scene configuration if needed.
  41434. if (!configuration) {
  41435. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41436. }
  41437. else {
  41438. this._imageProcessingConfiguration = configuration;
  41439. }
  41440. // Attaches observer.
  41441. if (this._imageProcessingConfiguration) {
  41442. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41443. _this._markAllSubMeshesAsImageProcessingDirty();
  41444. });
  41445. }
  41446. };
  41447. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41448. /**
  41449. * Gets wether the color curves effect is enabled.
  41450. */
  41451. get: function () {
  41452. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41453. },
  41454. /**
  41455. * Sets wether the color curves effect is enabled.
  41456. */
  41457. set: function (value) {
  41458. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41459. },
  41460. enumerable: true,
  41461. configurable: true
  41462. });
  41463. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41464. /**
  41465. * Gets wether the color grading effect is enabled.
  41466. */
  41467. get: function () {
  41468. return this.imageProcessingConfiguration.colorGradingEnabled;
  41469. },
  41470. /**
  41471. * Gets wether the color grading effect is enabled.
  41472. */
  41473. set: function (value) {
  41474. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41475. },
  41476. enumerable: true,
  41477. configurable: true
  41478. });
  41479. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41480. /**
  41481. * Gets wether tonemapping is enabled or not.
  41482. */
  41483. get: function () {
  41484. return this._imageProcessingConfiguration.toneMappingEnabled;
  41485. },
  41486. /**
  41487. * Sets wether tonemapping is enabled or not
  41488. */
  41489. set: function (value) {
  41490. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41491. },
  41492. enumerable: true,
  41493. configurable: true
  41494. });
  41495. ;
  41496. ;
  41497. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41498. /**
  41499. * The camera exposure used on this material.
  41500. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41501. * This corresponds to a photographic exposure.
  41502. */
  41503. get: function () {
  41504. return this._imageProcessingConfiguration.exposure;
  41505. },
  41506. /**
  41507. * The camera exposure used on this material.
  41508. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41509. * This corresponds to a photographic exposure.
  41510. */
  41511. set: function (value) {
  41512. this._imageProcessingConfiguration.exposure = value;
  41513. },
  41514. enumerable: true,
  41515. configurable: true
  41516. });
  41517. ;
  41518. ;
  41519. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41520. /**
  41521. * Gets The camera contrast used on this material.
  41522. */
  41523. get: function () {
  41524. return this._imageProcessingConfiguration.contrast;
  41525. },
  41526. /**
  41527. * Sets The camera contrast used on this material.
  41528. */
  41529. set: function (value) {
  41530. this._imageProcessingConfiguration.contrast = value;
  41531. },
  41532. enumerable: true,
  41533. configurable: true
  41534. });
  41535. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41536. /**
  41537. * Gets the Color Grading 2D Lookup Texture.
  41538. */
  41539. get: function () {
  41540. return this._imageProcessingConfiguration.colorGradingTexture;
  41541. },
  41542. /**
  41543. * Sets the Color Grading 2D Lookup Texture.
  41544. */
  41545. set: function (value) {
  41546. this._imageProcessingConfiguration.colorGradingTexture = value;
  41547. },
  41548. enumerable: true,
  41549. configurable: true
  41550. });
  41551. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41552. /**
  41553. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41554. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41555. * 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;
  41556. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41557. */
  41558. get: function () {
  41559. return this._imageProcessingConfiguration.colorCurves;
  41560. },
  41561. /**
  41562. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41563. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41564. * 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;
  41565. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41566. */
  41567. set: function (value) {
  41568. this._imageProcessingConfiguration.colorCurves = value;
  41569. },
  41570. enumerable: true,
  41571. configurable: true
  41572. });
  41573. StandardMaterial.prototype.getClassName = function () {
  41574. return "StandardMaterial";
  41575. };
  41576. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41577. get: function () {
  41578. return this._useLogarithmicDepth;
  41579. },
  41580. set: function (value) {
  41581. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41582. this._markAllSubMeshesAsMiscDirty();
  41583. },
  41584. enumerable: true,
  41585. configurable: true
  41586. });
  41587. StandardMaterial.prototype.needAlphaBlending = function () {
  41588. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41589. };
  41590. StandardMaterial.prototype.needAlphaTesting = function () {
  41591. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41592. };
  41593. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41594. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41595. };
  41596. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41597. return this._diffuseTexture;
  41598. };
  41599. /**
  41600. * Child classes can use it to update shaders
  41601. */
  41602. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41603. if (useInstances === void 0) { useInstances = false; }
  41604. if (subMesh.effect && this.isFrozen) {
  41605. if (this._wasPreviouslyReady && subMesh.effect) {
  41606. return true;
  41607. }
  41608. }
  41609. if (!subMesh._materialDefines) {
  41610. subMesh._materialDefines = new StandardMaterialDefines();
  41611. }
  41612. var scene = this.getScene();
  41613. var defines = subMesh._materialDefines;
  41614. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41615. if (defines._renderId === scene.getRenderId()) {
  41616. return true;
  41617. }
  41618. }
  41619. var engine = scene.getEngine();
  41620. // Lights
  41621. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41622. // Textures
  41623. if (defines._areTexturesDirty) {
  41624. defines._needUVs = false;
  41625. defines.MAINUV1 = false;
  41626. defines.MAINUV2 = false;
  41627. if (scene.texturesEnabled) {
  41628. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41629. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41630. return false;
  41631. }
  41632. else {
  41633. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41634. }
  41635. }
  41636. else {
  41637. defines.DIFFUSE = false;
  41638. }
  41639. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41640. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41641. return false;
  41642. }
  41643. else {
  41644. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41645. }
  41646. }
  41647. else {
  41648. defines.AMBIENT = false;
  41649. }
  41650. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41651. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41652. return false;
  41653. }
  41654. else {
  41655. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41656. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41657. }
  41658. }
  41659. else {
  41660. defines.OPACITY = false;
  41661. }
  41662. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41663. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41664. return false;
  41665. }
  41666. else {
  41667. defines._needNormals = true;
  41668. defines.REFLECTION = true;
  41669. defines.ROUGHNESS = (this._roughness > 0);
  41670. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41671. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41672. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41673. switch (this._reflectionTexture.coordinatesMode) {
  41674. case BABYLON.Texture.EXPLICIT_MODE:
  41675. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41676. break;
  41677. case BABYLON.Texture.PLANAR_MODE:
  41678. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41679. break;
  41680. case BABYLON.Texture.PROJECTION_MODE:
  41681. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41682. break;
  41683. case BABYLON.Texture.SKYBOX_MODE:
  41684. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41685. break;
  41686. case BABYLON.Texture.SPHERICAL_MODE:
  41687. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41688. break;
  41689. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41690. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41691. break;
  41692. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41693. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41694. break;
  41695. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41696. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41697. break;
  41698. case BABYLON.Texture.CUBIC_MODE:
  41699. case BABYLON.Texture.INVCUBIC_MODE:
  41700. default:
  41701. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41702. break;
  41703. }
  41704. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41705. }
  41706. }
  41707. else {
  41708. defines.REFLECTION = false;
  41709. }
  41710. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41711. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41712. return false;
  41713. }
  41714. else {
  41715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41716. }
  41717. }
  41718. else {
  41719. defines.EMISSIVE = false;
  41720. }
  41721. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41722. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41723. return false;
  41724. }
  41725. else {
  41726. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41727. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41728. }
  41729. }
  41730. else {
  41731. defines.LIGHTMAP = false;
  41732. }
  41733. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41734. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41735. return false;
  41736. }
  41737. else {
  41738. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41739. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41740. }
  41741. }
  41742. else {
  41743. defines.SPECULAR = false;
  41744. }
  41745. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41746. // Bump texure can not be not blocking.
  41747. if (!this._bumpTexture.isReady()) {
  41748. return false;
  41749. }
  41750. else {
  41751. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41752. defines.PARALLAX = this._useParallax;
  41753. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41754. }
  41755. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41756. }
  41757. else {
  41758. defines.BUMP = false;
  41759. }
  41760. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41761. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41762. return false;
  41763. }
  41764. else {
  41765. defines._needUVs = true;
  41766. defines.REFRACTION = true;
  41767. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41768. }
  41769. }
  41770. else {
  41771. defines.REFRACTION = false;
  41772. }
  41773. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41774. }
  41775. else {
  41776. defines.DIFFUSE = false;
  41777. defines.AMBIENT = false;
  41778. defines.OPACITY = false;
  41779. defines.REFLECTION = false;
  41780. defines.EMISSIVE = false;
  41781. defines.LIGHTMAP = false;
  41782. defines.BUMP = false;
  41783. defines.REFRACTION = false;
  41784. }
  41785. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41786. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41787. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41788. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41789. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41790. }
  41791. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41792. if (!this._imageProcessingConfiguration.isReady()) {
  41793. return false;
  41794. }
  41795. this._imageProcessingConfiguration.prepareDefines(defines);
  41796. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41797. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41798. }
  41799. if (defines._areFresnelDirty) {
  41800. if (StandardMaterial.FresnelEnabled) {
  41801. // Fresnel
  41802. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41803. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41804. this._reflectionFresnelParameters) {
  41805. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41806. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41807. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41808. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41809. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41810. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41811. defines._needNormals = true;
  41812. defines.FRESNEL = true;
  41813. }
  41814. }
  41815. else {
  41816. defines.FRESNEL = false;
  41817. }
  41818. }
  41819. // Misc.
  41820. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41821. // Attribs
  41822. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41823. // Values that need to be evaluated on every frame
  41824. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41825. // Get correct effect
  41826. if (defines.isDirty) {
  41827. defines.markAsProcessed();
  41828. scene.resetCachedMaterial();
  41829. // Fallbacks
  41830. var fallbacks = new BABYLON.EffectFallbacks();
  41831. if (defines.REFLECTION) {
  41832. fallbacks.addFallback(0, "REFLECTION");
  41833. }
  41834. if (defines.SPECULAR) {
  41835. fallbacks.addFallback(0, "SPECULAR");
  41836. }
  41837. if (defines.BUMP) {
  41838. fallbacks.addFallback(0, "BUMP");
  41839. }
  41840. if (defines.PARALLAX) {
  41841. fallbacks.addFallback(1, "PARALLAX");
  41842. }
  41843. if (defines.PARALLAXOCCLUSION) {
  41844. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41845. }
  41846. if (defines.SPECULAROVERALPHA) {
  41847. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41848. }
  41849. if (defines.FOG) {
  41850. fallbacks.addFallback(1, "FOG");
  41851. }
  41852. if (defines.POINTSIZE) {
  41853. fallbacks.addFallback(0, "POINTSIZE");
  41854. }
  41855. if (defines.LOGARITHMICDEPTH) {
  41856. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41857. }
  41858. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41859. if (defines.SPECULARTERM) {
  41860. fallbacks.addFallback(0, "SPECULARTERM");
  41861. }
  41862. if (defines.DIFFUSEFRESNEL) {
  41863. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41864. }
  41865. if (defines.OPACITYFRESNEL) {
  41866. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41867. }
  41868. if (defines.REFLECTIONFRESNEL) {
  41869. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41870. }
  41871. if (defines.EMISSIVEFRESNEL) {
  41872. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41873. }
  41874. if (defines.FRESNEL) {
  41875. fallbacks.addFallback(4, "FRESNEL");
  41876. }
  41877. //Attributes
  41878. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41879. if (defines.NORMAL) {
  41880. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41881. }
  41882. if (defines.UV1) {
  41883. attribs.push(BABYLON.VertexBuffer.UVKind);
  41884. }
  41885. if (defines.UV2) {
  41886. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41887. }
  41888. if (defines.VERTEXCOLOR) {
  41889. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41890. }
  41891. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41892. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41893. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41894. var shaderName = "default";
  41895. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41896. "vFogInfos", "vFogColor", "pointSize",
  41897. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41898. "mBones",
  41899. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41900. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41901. "vReflectionPosition", "vReflectionSize",
  41902. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41903. ];
  41904. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41905. var uniformBuffers = ["Material", "Scene"];
  41906. if (BABYLON.ImageProcessingConfiguration) {
  41907. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41908. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41909. }
  41910. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41911. uniformsNames: uniforms,
  41912. uniformBuffersNames: uniformBuffers,
  41913. samplers: samplers,
  41914. defines: defines,
  41915. maxSimultaneousLights: this._maxSimultaneousLights
  41916. });
  41917. if (this.customShaderNameResolve) {
  41918. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41919. }
  41920. var join = defines.toString();
  41921. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41922. attributes: attribs,
  41923. uniformsNames: uniforms,
  41924. uniformBuffersNames: uniformBuffers,
  41925. samplers: samplers,
  41926. defines: join,
  41927. fallbacks: fallbacks,
  41928. onCompiled: this.onCompiled,
  41929. onError: this.onError,
  41930. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41931. }, engine), defines);
  41932. this.buildUniformLayout();
  41933. }
  41934. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41935. return false;
  41936. }
  41937. defines._renderId = scene.getRenderId();
  41938. this._wasPreviouslyReady = true;
  41939. return true;
  41940. };
  41941. StandardMaterial.prototype.buildUniformLayout = function () {
  41942. // Order is important !
  41943. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41944. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41945. this._uniformBuffer.addUniform("opacityParts", 4);
  41946. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41947. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41948. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41949. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41950. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41951. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41952. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41953. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41954. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41955. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41956. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41957. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41958. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41959. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41960. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41961. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41962. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41963. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41964. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41965. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41966. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41967. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41968. this._uniformBuffer.addUniform("specularMatrix", 16);
  41969. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41970. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41971. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41972. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41973. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41974. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41975. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41976. this._uniformBuffer.addUniform("pointSize", 1);
  41977. this._uniformBuffer.create();
  41978. };
  41979. StandardMaterial.prototype.unbind = function () {
  41980. if (this._activeEffect) {
  41981. var needFlag = false;
  41982. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41983. this._activeEffect.setTexture("reflection2DSampler", null);
  41984. needFlag = true;
  41985. }
  41986. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41987. this._activeEffect.setTexture("refraction2DSampler", null);
  41988. needFlag = true;
  41989. }
  41990. if (needFlag) {
  41991. this._markAllSubMeshesAsTexturesDirty();
  41992. }
  41993. }
  41994. _super.prototype.unbind.call(this);
  41995. };
  41996. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41997. var scene = this.getScene();
  41998. var defines = subMesh._materialDefines;
  41999. if (!defines) {
  42000. return;
  42001. }
  42002. var effect = subMesh.effect;
  42003. if (!effect) {
  42004. return;
  42005. }
  42006. this._activeEffect = effect;
  42007. // Matrices
  42008. this.bindOnlyWorldMatrix(world);
  42009. // Normal Matrix
  42010. if (defines.OBJECTSPACE_NORMALMAP) {
  42011. world.toNormalMatrix(this._normalMatrix);
  42012. this.bindOnlyNormalMatrix(this._normalMatrix);
  42013. }
  42014. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42015. // Bones
  42016. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42017. if (mustRebind) {
  42018. this._uniformBuffer.bindToEffect(effect, "Material");
  42019. this.bindViewProjection(effect);
  42020. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42021. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42022. // Fresnel
  42023. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42024. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42025. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42026. }
  42027. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42028. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42029. }
  42030. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42031. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42032. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42033. }
  42034. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42035. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42036. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42037. }
  42038. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42039. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42040. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42041. }
  42042. }
  42043. // Textures
  42044. if (scene.texturesEnabled) {
  42045. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42046. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42047. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42048. if (this._diffuseTexture.hasAlpha) {
  42049. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42050. }
  42051. }
  42052. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42053. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42054. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42055. }
  42056. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42057. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42058. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42059. }
  42060. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42061. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42062. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42063. if (this._reflectionTexture.boundingBoxSize) {
  42064. var cubeTexture = this._reflectionTexture;
  42065. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42066. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42067. }
  42068. }
  42069. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42070. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42071. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42072. }
  42073. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42074. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42075. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42076. }
  42077. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42078. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42079. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42080. }
  42081. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42082. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42083. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42084. if (scene._mirroredCameraPosition) {
  42085. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42086. }
  42087. else {
  42088. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42089. }
  42090. }
  42091. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42092. var depth = 1.0;
  42093. if (!this._refractionTexture.isCube) {
  42094. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42095. if (this._refractionTexture.depth) {
  42096. depth = this._refractionTexture.depth;
  42097. }
  42098. }
  42099. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42100. }
  42101. }
  42102. // Point size
  42103. if (this.pointsCloud) {
  42104. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42105. }
  42106. if (defines.SPECULARTERM) {
  42107. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42108. }
  42109. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42110. // Diffuse
  42111. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42112. }
  42113. // Textures
  42114. if (scene.texturesEnabled) {
  42115. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42116. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42117. }
  42118. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42119. effect.setTexture("ambientSampler", this._ambientTexture);
  42120. }
  42121. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42122. effect.setTexture("opacitySampler", this._opacityTexture);
  42123. }
  42124. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42125. if (this._reflectionTexture.isCube) {
  42126. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42127. }
  42128. else {
  42129. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42130. }
  42131. }
  42132. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42133. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42134. }
  42135. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42136. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42137. }
  42138. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42139. effect.setTexture("specularSampler", this._specularTexture);
  42140. }
  42141. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42142. effect.setTexture("bumpSampler", this._bumpTexture);
  42143. }
  42144. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42145. var depth = 1.0;
  42146. if (this._refractionTexture.isCube) {
  42147. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42148. }
  42149. else {
  42150. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42151. }
  42152. }
  42153. }
  42154. // Clip plane
  42155. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42156. // Colors
  42157. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42158. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42159. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42160. }
  42161. if (mustRebind || !this.isFrozen) {
  42162. // Lights
  42163. if (scene.lightsEnabled && !this._disableLighting) {
  42164. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42165. }
  42166. // View
  42167. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42168. this.bindView(effect);
  42169. }
  42170. // Fog
  42171. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42172. // Morph targets
  42173. if (defines.NUM_MORPH_INFLUENCERS) {
  42174. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42175. }
  42176. // Log. depth
  42177. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42178. // image processing
  42179. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42180. this._imageProcessingConfiguration.bind(this._activeEffect);
  42181. }
  42182. }
  42183. this._uniformBuffer.update();
  42184. this._afterBind(mesh, this._activeEffect);
  42185. };
  42186. StandardMaterial.prototype.getAnimatables = function () {
  42187. var results = [];
  42188. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42189. results.push(this._diffuseTexture);
  42190. }
  42191. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42192. results.push(this._ambientTexture);
  42193. }
  42194. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42195. results.push(this._opacityTexture);
  42196. }
  42197. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42198. results.push(this._reflectionTexture);
  42199. }
  42200. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42201. results.push(this._emissiveTexture);
  42202. }
  42203. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42204. results.push(this._specularTexture);
  42205. }
  42206. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42207. results.push(this._bumpTexture);
  42208. }
  42209. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42210. results.push(this._lightmapTexture);
  42211. }
  42212. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42213. results.push(this._refractionTexture);
  42214. }
  42215. return results;
  42216. };
  42217. StandardMaterial.prototype.getActiveTextures = function () {
  42218. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42219. if (this._diffuseTexture) {
  42220. activeTextures.push(this._diffuseTexture);
  42221. }
  42222. if (this._ambientTexture) {
  42223. activeTextures.push(this._ambientTexture);
  42224. }
  42225. if (this._opacityTexture) {
  42226. activeTextures.push(this._opacityTexture);
  42227. }
  42228. if (this._reflectionTexture) {
  42229. activeTextures.push(this._reflectionTexture);
  42230. }
  42231. if (this._emissiveTexture) {
  42232. activeTextures.push(this._emissiveTexture);
  42233. }
  42234. if (this._specularTexture) {
  42235. activeTextures.push(this._specularTexture);
  42236. }
  42237. if (this._bumpTexture) {
  42238. activeTextures.push(this._bumpTexture);
  42239. }
  42240. if (this._lightmapTexture) {
  42241. activeTextures.push(this._lightmapTexture);
  42242. }
  42243. if (this._refractionTexture) {
  42244. activeTextures.push(this._refractionTexture);
  42245. }
  42246. return activeTextures;
  42247. };
  42248. StandardMaterial.prototype.hasTexture = function (texture) {
  42249. if (_super.prototype.hasTexture.call(this, texture)) {
  42250. return true;
  42251. }
  42252. if (this._diffuseTexture === texture) {
  42253. return true;
  42254. }
  42255. if (this._ambientTexture === texture) {
  42256. return true;
  42257. }
  42258. if (this._opacityTexture === texture) {
  42259. return true;
  42260. }
  42261. if (this._reflectionTexture === texture) {
  42262. return true;
  42263. }
  42264. if (this._emissiveTexture === texture) {
  42265. return true;
  42266. }
  42267. if (this._specularTexture === texture) {
  42268. return true;
  42269. }
  42270. if (this._bumpTexture === texture) {
  42271. return true;
  42272. }
  42273. if (this._lightmapTexture === texture) {
  42274. return true;
  42275. }
  42276. if (this._refractionTexture === texture) {
  42277. return true;
  42278. }
  42279. return false;
  42280. };
  42281. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42282. if (forceDisposeTextures) {
  42283. if (this._diffuseTexture) {
  42284. this._diffuseTexture.dispose();
  42285. }
  42286. if (this._ambientTexture) {
  42287. this._ambientTexture.dispose();
  42288. }
  42289. if (this._opacityTexture) {
  42290. this._opacityTexture.dispose();
  42291. }
  42292. if (this._reflectionTexture) {
  42293. this._reflectionTexture.dispose();
  42294. }
  42295. if (this._emissiveTexture) {
  42296. this._emissiveTexture.dispose();
  42297. }
  42298. if (this._specularTexture) {
  42299. this._specularTexture.dispose();
  42300. }
  42301. if (this._bumpTexture) {
  42302. this._bumpTexture.dispose();
  42303. }
  42304. if (this._lightmapTexture) {
  42305. this._lightmapTexture.dispose();
  42306. }
  42307. if (this._refractionTexture) {
  42308. this._refractionTexture.dispose();
  42309. }
  42310. }
  42311. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42312. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42313. }
  42314. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42315. };
  42316. StandardMaterial.prototype.clone = function (name) {
  42317. var _this = this;
  42318. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42319. result.name = name;
  42320. result.id = name;
  42321. return result;
  42322. };
  42323. StandardMaterial.prototype.serialize = function () {
  42324. return BABYLON.SerializationHelper.Serialize(this);
  42325. };
  42326. // Statics
  42327. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42328. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42329. };
  42330. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42331. get: function () {
  42332. return StandardMaterial._DiffuseTextureEnabled;
  42333. },
  42334. set: function (value) {
  42335. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42336. return;
  42337. }
  42338. StandardMaterial._DiffuseTextureEnabled = value;
  42339. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42340. },
  42341. enumerable: true,
  42342. configurable: true
  42343. });
  42344. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42345. get: function () {
  42346. return StandardMaterial._AmbientTextureEnabled;
  42347. },
  42348. set: function (value) {
  42349. if (StandardMaterial._AmbientTextureEnabled === value) {
  42350. return;
  42351. }
  42352. StandardMaterial._AmbientTextureEnabled = value;
  42353. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42354. },
  42355. enumerable: true,
  42356. configurable: true
  42357. });
  42358. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42359. get: function () {
  42360. return StandardMaterial._OpacityTextureEnabled;
  42361. },
  42362. set: function (value) {
  42363. if (StandardMaterial._OpacityTextureEnabled === value) {
  42364. return;
  42365. }
  42366. StandardMaterial._OpacityTextureEnabled = value;
  42367. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42368. },
  42369. enumerable: true,
  42370. configurable: true
  42371. });
  42372. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42373. get: function () {
  42374. return StandardMaterial._ReflectionTextureEnabled;
  42375. },
  42376. set: function (value) {
  42377. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42378. return;
  42379. }
  42380. StandardMaterial._ReflectionTextureEnabled = value;
  42381. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42382. },
  42383. enumerable: true,
  42384. configurable: true
  42385. });
  42386. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42387. get: function () {
  42388. return StandardMaterial._EmissiveTextureEnabled;
  42389. },
  42390. set: function (value) {
  42391. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42392. return;
  42393. }
  42394. StandardMaterial._EmissiveTextureEnabled = value;
  42395. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42396. },
  42397. enumerable: true,
  42398. configurable: true
  42399. });
  42400. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42401. get: function () {
  42402. return StandardMaterial._SpecularTextureEnabled;
  42403. },
  42404. set: function (value) {
  42405. if (StandardMaterial._SpecularTextureEnabled === value) {
  42406. return;
  42407. }
  42408. StandardMaterial._SpecularTextureEnabled = value;
  42409. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42410. },
  42411. enumerable: true,
  42412. configurable: true
  42413. });
  42414. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42415. get: function () {
  42416. return StandardMaterial._BumpTextureEnabled;
  42417. },
  42418. set: function (value) {
  42419. if (StandardMaterial._BumpTextureEnabled === value) {
  42420. return;
  42421. }
  42422. StandardMaterial._BumpTextureEnabled = value;
  42423. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42424. },
  42425. enumerable: true,
  42426. configurable: true
  42427. });
  42428. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42429. get: function () {
  42430. return StandardMaterial._LightmapTextureEnabled;
  42431. },
  42432. set: function (value) {
  42433. if (StandardMaterial._LightmapTextureEnabled === value) {
  42434. return;
  42435. }
  42436. StandardMaterial._LightmapTextureEnabled = value;
  42437. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42438. },
  42439. enumerable: true,
  42440. configurable: true
  42441. });
  42442. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42443. get: function () {
  42444. return StandardMaterial._RefractionTextureEnabled;
  42445. },
  42446. set: function (value) {
  42447. if (StandardMaterial._RefractionTextureEnabled === value) {
  42448. return;
  42449. }
  42450. StandardMaterial._RefractionTextureEnabled = value;
  42451. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42452. },
  42453. enumerable: true,
  42454. configurable: true
  42455. });
  42456. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42457. get: function () {
  42458. return StandardMaterial._ColorGradingTextureEnabled;
  42459. },
  42460. set: function (value) {
  42461. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42462. return;
  42463. }
  42464. StandardMaterial._ColorGradingTextureEnabled = value;
  42465. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42471. get: function () {
  42472. return StandardMaterial._FresnelEnabled;
  42473. },
  42474. set: function (value) {
  42475. if (StandardMaterial._FresnelEnabled === value) {
  42476. return;
  42477. }
  42478. StandardMaterial._FresnelEnabled = value;
  42479. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42480. },
  42481. enumerable: true,
  42482. configurable: true
  42483. });
  42484. // Flags used to enable or disable a type of texture for all Standard Materials
  42485. StandardMaterial._DiffuseTextureEnabled = true;
  42486. StandardMaterial._AmbientTextureEnabled = true;
  42487. StandardMaterial._OpacityTextureEnabled = true;
  42488. StandardMaterial._ReflectionTextureEnabled = true;
  42489. StandardMaterial._EmissiveTextureEnabled = true;
  42490. StandardMaterial._SpecularTextureEnabled = true;
  42491. StandardMaterial._BumpTextureEnabled = true;
  42492. StandardMaterial._LightmapTextureEnabled = true;
  42493. StandardMaterial._RefractionTextureEnabled = true;
  42494. StandardMaterial._ColorGradingTextureEnabled = true;
  42495. StandardMaterial._FresnelEnabled = true;
  42496. __decorate([
  42497. BABYLON.serializeAsTexture("diffuseTexture")
  42498. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42499. __decorate([
  42500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42501. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42502. __decorate([
  42503. BABYLON.serializeAsTexture("ambientTexture")
  42504. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42505. __decorate([
  42506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42507. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42508. __decorate([
  42509. BABYLON.serializeAsTexture("opacityTexture")
  42510. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42511. __decorate([
  42512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42513. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42514. __decorate([
  42515. BABYLON.serializeAsTexture("reflectionTexture")
  42516. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42517. __decorate([
  42518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42519. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42520. __decorate([
  42521. BABYLON.serializeAsTexture("emissiveTexture")
  42522. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42523. __decorate([
  42524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42525. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42526. __decorate([
  42527. BABYLON.serializeAsTexture("specularTexture")
  42528. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42529. __decorate([
  42530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42531. ], StandardMaterial.prototype, "specularTexture", void 0);
  42532. __decorate([
  42533. BABYLON.serializeAsTexture("bumpTexture")
  42534. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42535. __decorate([
  42536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42537. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42538. __decorate([
  42539. BABYLON.serializeAsTexture("lightmapTexture")
  42540. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42541. __decorate([
  42542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42543. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42544. __decorate([
  42545. BABYLON.serializeAsTexture("refractionTexture")
  42546. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42547. __decorate([
  42548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42549. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42550. __decorate([
  42551. BABYLON.serializeAsColor3("ambient")
  42552. ], StandardMaterial.prototype, "ambientColor", void 0);
  42553. __decorate([
  42554. BABYLON.serializeAsColor3("diffuse")
  42555. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42556. __decorate([
  42557. BABYLON.serializeAsColor3("specular")
  42558. ], StandardMaterial.prototype, "specularColor", void 0);
  42559. __decorate([
  42560. BABYLON.serializeAsColor3("emissive")
  42561. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42562. __decorate([
  42563. BABYLON.serialize()
  42564. ], StandardMaterial.prototype, "specularPower", void 0);
  42565. __decorate([
  42566. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42567. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42568. __decorate([
  42569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42570. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42571. __decorate([
  42572. BABYLON.serialize("useEmissiveAsIllumination")
  42573. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42574. __decorate([
  42575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42576. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42577. __decorate([
  42578. BABYLON.serialize("linkEmissiveWithDiffuse")
  42579. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42580. __decorate([
  42581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42582. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42583. __decorate([
  42584. BABYLON.serialize("useSpecularOverAlpha")
  42585. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42586. __decorate([
  42587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42588. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42589. __decorate([
  42590. BABYLON.serialize("useReflectionOverAlpha")
  42591. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42592. __decorate([
  42593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42594. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42595. __decorate([
  42596. BABYLON.serialize("disableLighting")
  42597. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42598. __decorate([
  42599. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42600. ], StandardMaterial.prototype, "disableLighting", void 0);
  42601. __decorate([
  42602. BABYLON.serialize("useObjectSpaceNormalMap")
  42603. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42604. __decorate([
  42605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42606. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42607. __decorate([
  42608. BABYLON.serialize("useParallax")
  42609. ], StandardMaterial.prototype, "_useParallax", void 0);
  42610. __decorate([
  42611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42612. ], StandardMaterial.prototype, "useParallax", void 0);
  42613. __decorate([
  42614. BABYLON.serialize("useParallaxOcclusion")
  42615. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42616. __decorate([
  42617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42618. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42619. __decorate([
  42620. BABYLON.serialize()
  42621. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42622. __decorate([
  42623. BABYLON.serialize("roughness")
  42624. ], StandardMaterial.prototype, "_roughness", void 0);
  42625. __decorate([
  42626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42627. ], StandardMaterial.prototype, "roughness", void 0);
  42628. __decorate([
  42629. BABYLON.serialize()
  42630. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42631. __decorate([
  42632. BABYLON.serialize()
  42633. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42634. __decorate([
  42635. BABYLON.serialize()
  42636. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42637. __decorate([
  42638. BABYLON.serialize("useLightmapAsShadowmap")
  42639. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42640. __decorate([
  42641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42642. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42643. __decorate([
  42644. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42645. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42646. __decorate([
  42647. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42648. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42649. __decorate([
  42650. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42651. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42652. __decorate([
  42653. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42654. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42655. __decorate([
  42656. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42657. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42658. __decorate([
  42659. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42660. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42661. __decorate([
  42662. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42663. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42664. __decorate([
  42665. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42666. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42667. __decorate([
  42668. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42669. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42670. __decorate([
  42671. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42672. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42673. __decorate([
  42674. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42675. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42676. __decorate([
  42677. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42678. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42679. __decorate([
  42680. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42681. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42682. __decorate([
  42683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42684. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42685. __decorate([
  42686. BABYLON.serialize("maxSimultaneousLights")
  42687. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42688. __decorate([
  42689. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42690. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42691. __decorate([
  42692. BABYLON.serialize("invertNormalMapX")
  42693. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42694. __decorate([
  42695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42696. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42697. __decorate([
  42698. BABYLON.serialize("invertNormalMapY")
  42699. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42700. __decorate([
  42701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42702. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42703. __decorate([
  42704. BABYLON.serialize("twoSidedLighting")
  42705. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42706. __decorate([
  42707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42708. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42709. __decorate([
  42710. BABYLON.serialize()
  42711. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42712. return StandardMaterial;
  42713. }(BABYLON.PushMaterial));
  42714. BABYLON.StandardMaterial = StandardMaterial;
  42715. })(BABYLON || (BABYLON = {}));
  42716. //# sourceMappingURL=babylon.standardMaterial.js.map
  42717. var BABYLON;
  42718. (function (BABYLON) {
  42719. /**
  42720. * Class representing spherical polynomial coefficients to the 3rd degree
  42721. */
  42722. var SphericalPolynomial = /** @class */ (function () {
  42723. function SphericalPolynomial() {
  42724. /**
  42725. * The x coefficients of the spherical polynomial
  42726. */
  42727. this.x = BABYLON.Vector3.Zero();
  42728. /**
  42729. * The y coefficients of the spherical polynomial
  42730. */
  42731. this.y = BABYLON.Vector3.Zero();
  42732. /**
  42733. * The z coefficients of the spherical polynomial
  42734. */
  42735. this.z = BABYLON.Vector3.Zero();
  42736. /**
  42737. * The xx coefficients of the spherical polynomial
  42738. */
  42739. this.xx = BABYLON.Vector3.Zero();
  42740. /**
  42741. * The yy coefficients of the spherical polynomial
  42742. */
  42743. this.yy = BABYLON.Vector3.Zero();
  42744. /**
  42745. * The zz coefficients of the spherical polynomial
  42746. */
  42747. this.zz = BABYLON.Vector3.Zero();
  42748. /**
  42749. * The xy coefficients of the spherical polynomial
  42750. */
  42751. this.xy = BABYLON.Vector3.Zero();
  42752. /**
  42753. * The yz coefficients of the spherical polynomial
  42754. */
  42755. this.yz = BABYLON.Vector3.Zero();
  42756. /**
  42757. * The zx coefficients of the spherical polynomial
  42758. */
  42759. this.zx = BABYLON.Vector3.Zero();
  42760. }
  42761. /**
  42762. * Adds an ambient color to the spherical polynomial
  42763. * @param color the color to add
  42764. */
  42765. SphericalPolynomial.prototype.addAmbient = function (color) {
  42766. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42767. this.xx = this.xx.add(colorVector);
  42768. this.yy = this.yy.add(colorVector);
  42769. this.zz = this.zz.add(colorVector);
  42770. };
  42771. /**
  42772. * Scales the spherical polynomial by the given amount
  42773. * @param scale the amount to scale
  42774. */
  42775. SphericalPolynomial.prototype.scale = function (scale) {
  42776. this.x = this.x.scale(scale);
  42777. this.y = this.y.scale(scale);
  42778. this.z = this.z.scale(scale);
  42779. this.xx = this.xx.scale(scale);
  42780. this.yy = this.yy.scale(scale);
  42781. this.zz = this.zz.scale(scale);
  42782. this.yz = this.yz.scale(scale);
  42783. this.zx = this.zx.scale(scale);
  42784. this.xy = this.xy.scale(scale);
  42785. };
  42786. /**
  42787. * Gets the spherical polynomial from harmonics
  42788. * @param harmonics the spherical harmonics
  42789. * @returns the spherical polynomial
  42790. */
  42791. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42792. var result = new SphericalPolynomial();
  42793. result.x = harmonics.l11.scale(1.02333);
  42794. result.y = harmonics.l1_1.scale(1.02333);
  42795. result.z = harmonics.l10.scale(1.02333);
  42796. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42797. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42798. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42799. result.yz = harmonics.l2_1.scale(0.858086);
  42800. result.zx = harmonics.l21.scale(0.858086);
  42801. result.xy = harmonics.l2_2.scale(0.858086);
  42802. result.scale(1.0 / Math.PI);
  42803. return result;
  42804. };
  42805. /**
  42806. * Constructs a spherical polynomial from an array.
  42807. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42808. * @returns the spherical polynomial
  42809. */
  42810. SphericalPolynomial.FromArray = function (data) {
  42811. var sp = new SphericalPolynomial();
  42812. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42813. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42814. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42815. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42816. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42817. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42818. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42819. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42820. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42821. return sp;
  42822. };
  42823. return SphericalPolynomial;
  42824. }());
  42825. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42826. /**
  42827. * Class representing spherical harmonics coefficients to the 3rd degree
  42828. */
  42829. var SphericalHarmonics = /** @class */ (function () {
  42830. function SphericalHarmonics() {
  42831. /**
  42832. * The l0,0 coefficients of the spherical harmonics
  42833. */
  42834. this.l00 = BABYLON.Vector3.Zero();
  42835. /**
  42836. * The l1,-1 coefficients of the spherical harmonics
  42837. */
  42838. this.l1_1 = BABYLON.Vector3.Zero();
  42839. /**
  42840. * The l1,0 coefficients of the spherical harmonics
  42841. */
  42842. this.l10 = BABYLON.Vector3.Zero();
  42843. /**
  42844. * The l1,1 coefficients of the spherical harmonics
  42845. */
  42846. this.l11 = BABYLON.Vector3.Zero();
  42847. /**
  42848. * The l2,-2 coefficients of the spherical harmonics
  42849. */
  42850. this.l2_2 = BABYLON.Vector3.Zero();
  42851. /**
  42852. * The l2,-1 coefficients of the spherical harmonics
  42853. */
  42854. this.l2_1 = BABYLON.Vector3.Zero();
  42855. /**
  42856. * The l2,0 coefficients of the spherical harmonics
  42857. */
  42858. this.l20 = BABYLON.Vector3.Zero();
  42859. /**
  42860. * The l2,1 coefficients of the spherical harmonics
  42861. */
  42862. this.l21 = BABYLON.Vector3.Zero();
  42863. /**
  42864. * The l2,2 coefficients of the spherical harmonics
  42865. */
  42866. this.lL22 = BABYLON.Vector3.Zero();
  42867. }
  42868. /**
  42869. * Adds a light to the spherical harmonics
  42870. * @param direction the direction of the light
  42871. * @param color the color of the light
  42872. * @param deltaSolidAngle the delta solid angle of the light
  42873. */
  42874. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42875. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42876. var c = colorVector.scale(deltaSolidAngle);
  42877. this.l00 = this.l00.add(c.scale(0.282095));
  42878. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42879. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42880. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42881. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42882. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42883. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42884. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42885. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42886. };
  42887. /**
  42888. * Scales the spherical harmonics by the given amount
  42889. * @param scale the amount to scale
  42890. */
  42891. SphericalHarmonics.prototype.scale = function (scale) {
  42892. this.l00 = this.l00.scale(scale);
  42893. this.l1_1 = this.l1_1.scale(scale);
  42894. this.l10 = this.l10.scale(scale);
  42895. this.l11 = this.l11.scale(scale);
  42896. this.l2_2 = this.l2_2.scale(scale);
  42897. this.l2_1 = this.l2_1.scale(scale);
  42898. this.l20 = this.l20.scale(scale);
  42899. this.l21 = this.l21.scale(scale);
  42900. this.lL22 = this.lL22.scale(scale);
  42901. };
  42902. /**
  42903. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42904. *
  42905. * ```
  42906. * E_lm = A_l * L_lm
  42907. * ```
  42908. *
  42909. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42910. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42911. * the scaling factors are given in equation 9.
  42912. */
  42913. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42914. // Constant (Band 0)
  42915. this.l00 = this.l00.scale(3.141593);
  42916. // Linear (Band 1)
  42917. this.l1_1 = this.l1_1.scale(2.094395);
  42918. this.l10 = this.l10.scale(2.094395);
  42919. this.l11 = this.l11.scale(2.094395);
  42920. // Quadratic (Band 2)
  42921. this.l2_2 = this.l2_2.scale(0.785398);
  42922. this.l2_1 = this.l2_1.scale(0.785398);
  42923. this.l20 = this.l20.scale(0.785398);
  42924. this.l21 = this.l21.scale(0.785398);
  42925. this.lL22 = this.lL22.scale(0.785398);
  42926. };
  42927. /**
  42928. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42929. *
  42930. * ```
  42931. * L = (1/pi) * E * rho
  42932. * ```
  42933. *
  42934. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42935. */
  42936. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42937. this.scale(1.0 / Math.PI);
  42938. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42939. // (The pixel shader must apply albedo after texture fetches, etc).
  42940. };
  42941. /**
  42942. * Gets the spherical harmonics from polynomial
  42943. * @param polynomial the spherical polynomial
  42944. * @returns the spherical harmonics
  42945. */
  42946. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42947. var result = new SphericalHarmonics();
  42948. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42949. result.l1_1 = polynomial.y.scale(0.977204);
  42950. result.l10 = polynomial.z.scale(0.977204);
  42951. result.l11 = polynomial.x.scale(0.977204);
  42952. result.l2_2 = polynomial.xy.scale(1.16538);
  42953. result.l2_1 = polynomial.yz.scale(1.16538);
  42954. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  42955. result.l21 = polynomial.zx.scale(1.16538);
  42956. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  42957. result.scale(Math.PI);
  42958. return result;
  42959. };
  42960. /**
  42961. * Constructs a spherical harmonics from an array.
  42962. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  42963. * @returns the spherical harmonics
  42964. */
  42965. SphericalHarmonics.FromArray = function (data) {
  42966. var sh = new SphericalHarmonics();
  42967. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  42968. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  42969. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  42970. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  42971. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  42972. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  42973. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  42974. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  42975. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  42976. return sh;
  42977. };
  42978. return SphericalHarmonics;
  42979. }());
  42980. BABYLON.SphericalHarmonics = SphericalHarmonics;
  42981. })(BABYLON || (BABYLON = {}));
  42982. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  42983. var BABYLON;
  42984. (function (BABYLON) {
  42985. var FileFaceOrientation = /** @class */ (function () {
  42986. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42987. this.name = name;
  42988. this.worldAxisForNormal = worldAxisForNormal;
  42989. this.worldAxisForFileX = worldAxisForFileX;
  42990. this.worldAxisForFileY = worldAxisForFileY;
  42991. }
  42992. return FileFaceOrientation;
  42993. }());
  42994. ;
  42995. /**
  42996. * Helper class dealing with the extraction of spherical polynomial dataArray
  42997. * from a cube map.
  42998. */
  42999. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43000. function CubeMapToSphericalPolynomialTools() {
  43001. }
  43002. /**
  43003. * Converts a texture to the according Spherical Polynomial data.
  43004. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43005. *
  43006. * @param texture The texture to extract the information from.
  43007. * @return The Spherical Polynomial data.
  43008. */
  43009. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43010. if (!texture.isCube) {
  43011. // Only supports cube Textures currently.
  43012. return null;
  43013. }
  43014. var size = texture.getSize().width;
  43015. var right = texture.readPixels(0);
  43016. var left = texture.readPixels(1);
  43017. var up;
  43018. var down;
  43019. if (texture.isRenderTarget) {
  43020. up = texture.readPixels(3);
  43021. down = texture.readPixels(2);
  43022. }
  43023. else {
  43024. up = texture.readPixels(2);
  43025. down = texture.readPixels(3);
  43026. }
  43027. var front = texture.readPixels(4);
  43028. var back = texture.readPixels(5);
  43029. var gammaSpace = texture.gammaSpace;
  43030. // Always read as RGBA.
  43031. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43032. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43033. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43034. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43035. }
  43036. var cubeInfo = {
  43037. size: size,
  43038. right: right,
  43039. left: left,
  43040. up: up,
  43041. down: down,
  43042. front: front,
  43043. back: back,
  43044. format: format,
  43045. type: type,
  43046. gammaSpace: gammaSpace,
  43047. };
  43048. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43049. };
  43050. /**
  43051. * Converts a cubemap to the according Spherical Polynomial data.
  43052. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43053. *
  43054. * @param cubeInfo The Cube map to extract the information from.
  43055. * @return The Spherical Polynomial data.
  43056. */
  43057. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43058. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43059. var totalSolidAngle = 0.0;
  43060. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43061. var du = 2.0 / cubeInfo.size;
  43062. var dv = du;
  43063. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43064. var minUV = du * 0.5 - 1.0;
  43065. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43066. var fileFace = this.FileFaces[faceIndex];
  43067. var dataArray = cubeInfo[fileFace.name];
  43068. var v = minUV;
  43069. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43070. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43071. // Because SP is still linear, so summation is fine in that basis.
  43072. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43073. for (var y = 0; y < cubeInfo.size; y++) {
  43074. var u = minUV;
  43075. for (var x = 0; x < cubeInfo.size; x++) {
  43076. // World direction (not normalised)
  43077. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43078. worldDirection.normalize();
  43079. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43080. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43081. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43082. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43083. // Handle Integer types.
  43084. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43085. r /= 255;
  43086. g /= 255;
  43087. b /= 255;
  43088. }
  43089. // Handle Gamma space textures.
  43090. if (cubeInfo.gammaSpace) {
  43091. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43092. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43093. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43094. }
  43095. var color = new BABYLON.Color3(r, g, b);
  43096. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43097. totalSolidAngle += deltaSolidAngle;
  43098. u += du;
  43099. }
  43100. v += dv;
  43101. }
  43102. }
  43103. // Solid angle for entire sphere is 4*pi
  43104. var sphereSolidAngle = 4.0 * Math.PI;
  43105. // Adjust the solid angle to allow for how many faces we processed.
  43106. var facesProcessed = 6.0;
  43107. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43108. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43109. // This is needed because the numerical integration over the cube uses a
  43110. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43111. // and also to compensate for accumulative error due to float precision in the summation.
  43112. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43113. sphericalHarmonics.scale(correctionFactor);
  43114. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43115. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43116. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43117. };
  43118. CubeMapToSphericalPolynomialTools.FileFaces = [
  43119. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43120. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43121. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43122. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43123. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43124. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43125. ];
  43126. return CubeMapToSphericalPolynomialTools;
  43127. }());
  43128. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43129. })(BABYLON || (BABYLON = {}));
  43130. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43131. var BABYLON;
  43132. (function (BABYLON) {
  43133. /**
  43134. * Manages the defines for the PBR Material.
  43135. * @hiddenChildren
  43136. */
  43137. var PBRMaterialDefines = /** @class */ (function (_super) {
  43138. __extends(PBRMaterialDefines, _super);
  43139. /**
  43140. * Initializes the PBR Material defines.
  43141. */
  43142. function PBRMaterialDefines() {
  43143. var _this = _super.call(this) || this;
  43144. _this.PBR = true;
  43145. _this.MAINUV1 = false;
  43146. _this.MAINUV2 = false;
  43147. _this.UV1 = false;
  43148. _this.UV2 = false;
  43149. _this.ALBEDO = false;
  43150. _this.ALBEDODIRECTUV = 0;
  43151. _this.VERTEXCOLOR = false;
  43152. _this.AMBIENT = false;
  43153. _this.AMBIENTDIRECTUV = 0;
  43154. _this.AMBIENTINGRAYSCALE = false;
  43155. _this.OPACITY = false;
  43156. _this.VERTEXALPHA = false;
  43157. _this.OPACITYDIRECTUV = 0;
  43158. _this.OPACITYRGB = false;
  43159. _this.ALPHATEST = false;
  43160. _this.DEPTHPREPASS = false;
  43161. _this.ALPHABLEND = false;
  43162. _this.ALPHAFROMALBEDO = false;
  43163. _this.ALPHATESTVALUE = "0.5";
  43164. _this.SPECULAROVERALPHA = false;
  43165. _this.RADIANCEOVERALPHA = false;
  43166. _this.ALPHAFRESNEL = false;
  43167. _this.LINEARALPHAFRESNEL = false;
  43168. _this.PREMULTIPLYALPHA = false;
  43169. _this.EMISSIVE = false;
  43170. _this.EMISSIVEDIRECTUV = 0;
  43171. _this.REFLECTIVITY = false;
  43172. _this.REFLECTIVITYDIRECTUV = 0;
  43173. _this.SPECULARTERM = false;
  43174. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43175. _this.MICROSURFACEAUTOMATIC = false;
  43176. _this.LODBASEDMICROSFURACE = false;
  43177. _this.MICROSURFACEMAP = false;
  43178. _this.MICROSURFACEMAPDIRECTUV = 0;
  43179. _this.METALLICWORKFLOW = false;
  43180. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43181. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43182. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43183. _this.AOSTOREINMETALMAPRED = false;
  43184. _this.ENVIRONMENTBRDF = false;
  43185. _this.NORMAL = false;
  43186. _this.TANGENT = false;
  43187. _this.BUMP = false;
  43188. _this.BUMPDIRECTUV = 0;
  43189. _this.OBJECTSPACE_NORMALMAP = false;
  43190. _this.PARALLAX = false;
  43191. _this.PARALLAXOCCLUSION = false;
  43192. _this.NORMALXYSCALE = true;
  43193. _this.LIGHTMAP = false;
  43194. _this.LIGHTMAPDIRECTUV = 0;
  43195. _this.USELIGHTMAPASSHADOWMAP = false;
  43196. _this.GAMMALIGHTMAP = false;
  43197. _this.REFLECTION = false;
  43198. _this.REFLECTIONMAP_3D = false;
  43199. _this.REFLECTIONMAP_SPHERICAL = false;
  43200. _this.REFLECTIONMAP_PLANAR = false;
  43201. _this.REFLECTIONMAP_CUBIC = false;
  43202. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43203. _this.REFLECTIONMAP_PROJECTION = false;
  43204. _this.REFLECTIONMAP_SKYBOX = false;
  43205. _this.REFLECTIONMAP_EXPLICIT = false;
  43206. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43207. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43208. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43209. _this.INVERTCUBICMAP = false;
  43210. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43211. _this.USESPHERICALINVERTEX = false;
  43212. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43213. _this.LODINREFLECTIONALPHA = false;
  43214. _this.GAMMAREFLECTION = false;
  43215. _this.RGBDREFLECTION = false;
  43216. _this.RADIANCEOCCLUSION = false;
  43217. _this.HORIZONOCCLUSION = false;
  43218. _this.REFRACTION = false;
  43219. _this.REFRACTIONMAP_3D = false;
  43220. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43221. _this.LODINREFRACTIONALPHA = false;
  43222. _this.GAMMAREFRACTION = false;
  43223. _this.RGBDREFRACTION = false;
  43224. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43225. _this.INSTANCES = false;
  43226. _this.NUM_BONE_INFLUENCERS = 0;
  43227. _this.BonesPerMesh = 0;
  43228. _this.NONUNIFORMSCALING = false;
  43229. _this.MORPHTARGETS = false;
  43230. _this.MORPHTARGETS_NORMAL = false;
  43231. _this.MORPHTARGETS_TANGENT = false;
  43232. _this.NUM_MORPH_INFLUENCERS = 0;
  43233. _this.IMAGEPROCESSING = false;
  43234. _this.VIGNETTE = false;
  43235. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43236. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43237. _this.TONEMAPPING = false;
  43238. _this.CONTRAST = false;
  43239. _this.COLORCURVES = false;
  43240. _this.COLORGRADING = false;
  43241. _this.COLORGRADING3D = false;
  43242. _this.SAMPLER3DGREENDEPTH = false;
  43243. _this.SAMPLER3DBGRMAP = false;
  43244. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43245. _this.EXPOSURE = false;
  43246. _this.USEPHYSICALLIGHTFALLOFF = false;
  43247. _this.TWOSIDEDLIGHTING = false;
  43248. _this.SHADOWFLOAT = false;
  43249. _this.CLIPPLANE = false;
  43250. _this.POINTSIZE = false;
  43251. _this.FOG = false;
  43252. _this.LOGARITHMICDEPTH = false;
  43253. _this.FORCENORMALFORWARD = false;
  43254. _this.SPECULARAA = false;
  43255. _this.UNLIT = false;
  43256. _this.rebuild();
  43257. return _this;
  43258. }
  43259. /**
  43260. * Resets the PBR Material defines.
  43261. */
  43262. PBRMaterialDefines.prototype.reset = function () {
  43263. _super.prototype.reset.call(this);
  43264. this.ALPHATESTVALUE = "0.5";
  43265. this.PBR = true;
  43266. };
  43267. return PBRMaterialDefines;
  43268. }(BABYLON.MaterialDefines));
  43269. /**
  43270. * The Physically based material base class of BJS.
  43271. *
  43272. * This offers the main features of a standard PBR material.
  43273. * For more information, please refer to the documentation :
  43274. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43275. */
  43276. var PBRBaseMaterial = /** @class */ (function (_super) {
  43277. __extends(PBRBaseMaterial, _super);
  43278. /**
  43279. * Instantiates a new PBRMaterial instance.
  43280. *
  43281. * @param name The material name
  43282. * @param scene The scene the material will be use in.
  43283. */
  43284. function PBRBaseMaterial(name, scene) {
  43285. var _this = _super.call(this, name, scene) || this;
  43286. /**
  43287. * Intensity of the direct lights e.g. the four lights available in your scene.
  43288. * This impacts both the direct diffuse and specular highlights.
  43289. */
  43290. _this._directIntensity = 1.0;
  43291. /**
  43292. * Intensity of the emissive part of the material.
  43293. * This helps controlling the emissive effect without modifying the emissive color.
  43294. */
  43295. _this._emissiveIntensity = 1.0;
  43296. /**
  43297. * Intensity of the environment e.g. how much the environment will light the object
  43298. * either through harmonics for rough material or through the refelction for shiny ones.
  43299. */
  43300. _this._environmentIntensity = 1.0;
  43301. /**
  43302. * This is a special control allowing the reduction of the specular highlights coming from the
  43303. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43304. */
  43305. _this._specularIntensity = 1.0;
  43306. /**
  43307. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43308. */
  43309. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43310. /**
  43311. * Debug Control allowing disabling the bump map on this material.
  43312. */
  43313. _this._disableBumpMap = false;
  43314. /**
  43315. * AKA Occlusion Texture Intensity in other nomenclature.
  43316. */
  43317. _this._ambientTextureStrength = 1.0;
  43318. /**
  43319. * The color of a material in ambient lighting.
  43320. */
  43321. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43322. /**
  43323. * AKA Diffuse Color in other nomenclature.
  43324. */
  43325. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43326. /**
  43327. * AKA Specular Color in other nomenclature.
  43328. */
  43329. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43330. /**
  43331. * The color applied when light is reflected from a material.
  43332. */
  43333. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43334. /**
  43335. * The color applied when light is emitted from a material.
  43336. */
  43337. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43338. /**
  43339. * AKA Glossiness in other nomenclature.
  43340. */
  43341. _this._microSurface = 0.9;
  43342. /**
  43343. * source material index of refraction (IOR)' / 'destination material IOR.
  43344. */
  43345. _this._indexOfRefraction = 0.66;
  43346. /**
  43347. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43348. */
  43349. _this._invertRefractionY = false;
  43350. /**
  43351. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43352. * Materials half opaque for instance using refraction could benefit from this control.
  43353. */
  43354. _this._linkRefractionWithTransparency = false;
  43355. /**
  43356. * Specifies that the material will use the light map as a show map.
  43357. */
  43358. _this._useLightmapAsShadowmap = false;
  43359. /**
  43360. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43361. * makes the reflect vector face the model (under horizon).
  43362. */
  43363. _this._useHorizonOcclusion = true;
  43364. /**
  43365. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43366. * too much the area relying on ambient texture to define their ambient occlusion.
  43367. */
  43368. _this._useRadianceOcclusion = true;
  43369. /**
  43370. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43371. */
  43372. _this._useAlphaFromAlbedoTexture = false;
  43373. /**
  43374. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43375. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43376. */
  43377. _this._useSpecularOverAlpha = true;
  43378. /**
  43379. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43380. */
  43381. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43382. /**
  43383. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43384. */
  43385. _this._useRoughnessFromMetallicTextureAlpha = true;
  43386. /**
  43387. * Specifies if the metallic texture contains the roughness information in its green channel.
  43388. */
  43389. _this._useRoughnessFromMetallicTextureGreen = false;
  43390. /**
  43391. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43392. */
  43393. _this._useMetallnessFromMetallicTextureBlue = false;
  43394. /**
  43395. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43396. */
  43397. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43398. /**
  43399. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43400. */
  43401. _this._useAmbientInGrayScale = false;
  43402. /**
  43403. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43404. * The material will try to infer what glossiness each pixel should be.
  43405. */
  43406. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43407. /**
  43408. * BJS is using an harcoded light falloff based on a manually sets up range.
  43409. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43410. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43411. */
  43412. _this._usePhysicalLightFalloff = true;
  43413. /**
  43414. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43415. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43416. */
  43417. _this._useRadianceOverAlpha = true;
  43418. /**
  43419. * Allows using an object space normal map (instead of tangent space).
  43420. */
  43421. _this._useObjectSpaceNormalMap = false;
  43422. /**
  43423. * Allows using the bump map in parallax mode.
  43424. */
  43425. _this._useParallax = false;
  43426. /**
  43427. * Allows using the bump map in parallax occlusion mode.
  43428. */
  43429. _this._useParallaxOcclusion = false;
  43430. /**
  43431. * Controls the scale bias of the parallax mode.
  43432. */
  43433. _this._parallaxScaleBias = 0.05;
  43434. /**
  43435. * If sets to true, disables all the lights affecting the material.
  43436. */
  43437. _this._disableLighting = false;
  43438. /**
  43439. * Number of Simultaneous lights allowed on the material.
  43440. */
  43441. _this._maxSimultaneousLights = 4;
  43442. /**
  43443. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43444. */
  43445. _this._invertNormalMapX = false;
  43446. /**
  43447. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43448. */
  43449. _this._invertNormalMapY = false;
  43450. /**
  43451. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43452. */
  43453. _this._twoSidedLighting = false;
  43454. /**
  43455. * Defines the alpha limits in alpha test mode.
  43456. */
  43457. _this._alphaCutOff = 0.4;
  43458. /**
  43459. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43460. */
  43461. _this._forceAlphaTest = false;
  43462. /**
  43463. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43464. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43465. */
  43466. _this._useAlphaFresnel = false;
  43467. /**
  43468. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43469. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43470. */
  43471. _this._useLinearAlphaFresnel = false;
  43472. /**
  43473. * The transparency mode of the material.
  43474. */
  43475. _this._transparencyMode = null;
  43476. /**
  43477. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43478. * from cos thetav and roughness:
  43479. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43480. */
  43481. _this._environmentBRDFTexture = null;
  43482. /**
  43483. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43484. */
  43485. _this._forceIrradianceInFragment = false;
  43486. /**
  43487. * Force normal to face away from face.
  43488. */
  43489. _this._forceNormalForward = false;
  43490. /**
  43491. * Enables specular anti aliasing in the PBR shader.
  43492. * It will both interacts on the Geometry for analytical and IBL lighting.
  43493. * It also prefilter the roughness map based on the bump values.
  43494. */
  43495. _this._enableSpecularAntiAliasing = false;
  43496. /**
  43497. * Stores the available render targets.
  43498. */
  43499. _this._renderTargets = new BABYLON.SmartArray(16);
  43500. /**
  43501. * Sets the global ambient color for the material used in lighting calculations.
  43502. */
  43503. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43504. /**
  43505. * If set to true, no lighting calculations will be applied.
  43506. */
  43507. _this._unlit = false;
  43508. // Setup the default processing configuration to the scene.
  43509. _this._attachImageProcessingConfiguration(null);
  43510. _this.getRenderTargetTextures = function () {
  43511. _this._renderTargets.reset();
  43512. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43513. _this._renderTargets.push(_this._reflectionTexture);
  43514. }
  43515. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43516. _this._renderTargets.push(_this._refractionTexture);
  43517. }
  43518. return _this._renderTargets;
  43519. };
  43520. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43521. return _this;
  43522. }
  43523. /**
  43524. * Attaches a new image processing configuration to the PBR Material.
  43525. * @param configuration
  43526. */
  43527. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43528. var _this = this;
  43529. if (configuration === this._imageProcessingConfiguration) {
  43530. return;
  43531. }
  43532. // Detaches observer.
  43533. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43534. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43535. }
  43536. // Pick the scene configuration if needed.
  43537. if (!configuration) {
  43538. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43539. }
  43540. else {
  43541. this._imageProcessingConfiguration = configuration;
  43542. }
  43543. // Attaches observer.
  43544. if (this._imageProcessingConfiguration) {
  43545. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43546. _this._markAllSubMeshesAsImageProcessingDirty();
  43547. });
  43548. }
  43549. };
  43550. /**
  43551. * Gets the name of the material class.
  43552. */
  43553. PBRBaseMaterial.prototype.getClassName = function () {
  43554. return "PBRBaseMaterial";
  43555. };
  43556. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43557. /**
  43558. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43559. */
  43560. get: function () {
  43561. return this._useLogarithmicDepth;
  43562. },
  43563. /**
  43564. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43565. */
  43566. set: function (value) {
  43567. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43568. },
  43569. enumerable: true,
  43570. configurable: true
  43571. });
  43572. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43573. /**
  43574. * Gets the current transparency mode.
  43575. */
  43576. get: function () {
  43577. return this._transparencyMode;
  43578. },
  43579. /**
  43580. * Sets the transparency mode of the material.
  43581. *
  43582. * | Value | Type | Description |
  43583. * | ----- | ----------------------------------- | ----------- |
  43584. * | 0 | OPAQUE | |
  43585. * | 1 | ALPHATEST | |
  43586. * | 2 | ALPHABLEND | |
  43587. * | 3 | ALPHATESTANDBLEND | |
  43588. *
  43589. */
  43590. set: function (value) {
  43591. if (this._transparencyMode === value) {
  43592. return;
  43593. }
  43594. this._transparencyMode = value;
  43595. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43596. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43597. },
  43598. enumerable: true,
  43599. configurable: true
  43600. });
  43601. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43602. /**
  43603. * Returns true if alpha blending should be disabled.
  43604. */
  43605. get: function () {
  43606. return (this._linkRefractionWithTransparency ||
  43607. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43608. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43609. },
  43610. enumerable: true,
  43611. configurable: true
  43612. });
  43613. /**
  43614. * Specifies whether or not this material should be rendered in alpha blend mode.
  43615. */
  43616. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43617. if (this._disableAlphaBlending) {
  43618. return false;
  43619. }
  43620. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43621. };
  43622. /**
  43623. * Specifies if the mesh will require alpha blending.
  43624. * @param mesh - BJS mesh.
  43625. */
  43626. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43627. if (this._disableAlphaBlending) {
  43628. return false;
  43629. }
  43630. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43631. };
  43632. /**
  43633. * Specifies whether or not this material should be rendered in alpha test mode.
  43634. */
  43635. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43636. if (this._forceAlphaTest) {
  43637. return true;
  43638. }
  43639. if (this._linkRefractionWithTransparency) {
  43640. return false;
  43641. }
  43642. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43643. };
  43644. /**
  43645. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43646. */
  43647. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43648. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43649. };
  43650. /**
  43651. * Gets the texture used for the alpha test.
  43652. */
  43653. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43654. return this._albedoTexture;
  43655. };
  43656. /**
  43657. * Specifies that the submesh is ready to be used.
  43658. * @param mesh - BJS mesh.
  43659. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43660. * @param useInstances - Specifies that instances should be used.
  43661. * @returns - boolean indicating that the submesh is ready or not.
  43662. */
  43663. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43664. if (subMesh.effect && this.isFrozen) {
  43665. if (this._wasPreviouslyReady) {
  43666. return true;
  43667. }
  43668. }
  43669. if (!subMesh._materialDefines) {
  43670. subMesh._materialDefines = new PBRMaterialDefines();
  43671. }
  43672. var defines = subMesh._materialDefines;
  43673. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43674. if (defines._renderId === this.getScene().getRenderId()) {
  43675. return true;
  43676. }
  43677. }
  43678. var scene = this.getScene();
  43679. var engine = scene.getEngine();
  43680. if (defines._areTexturesDirty) {
  43681. if (scene.texturesEnabled) {
  43682. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43683. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43684. return false;
  43685. }
  43686. }
  43687. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43688. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43689. return false;
  43690. }
  43691. }
  43692. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43693. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43694. return false;
  43695. }
  43696. }
  43697. var reflectionTexture = this._getReflectionTexture();
  43698. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43699. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43700. return false;
  43701. }
  43702. }
  43703. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43704. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43705. return false;
  43706. }
  43707. }
  43708. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43709. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43710. return false;
  43711. }
  43712. }
  43713. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43714. if (this._metallicTexture) {
  43715. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43716. return false;
  43717. }
  43718. }
  43719. else if (this._reflectivityTexture) {
  43720. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43721. return false;
  43722. }
  43723. }
  43724. if (this._microSurfaceTexture) {
  43725. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43726. return false;
  43727. }
  43728. }
  43729. }
  43730. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43731. // Bump texture cannot be not blocking.
  43732. if (!this._bumpTexture.isReady()) {
  43733. return false;
  43734. }
  43735. }
  43736. var refractionTexture = this._getRefractionTexture();
  43737. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43738. if (!refractionTexture.isReadyOrNotBlocking()) {
  43739. return false;
  43740. }
  43741. }
  43742. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43743. // This is blocking.
  43744. if (!this._environmentBRDFTexture.isReady()) {
  43745. return false;
  43746. }
  43747. }
  43748. }
  43749. }
  43750. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43751. if (!this._imageProcessingConfiguration.isReady()) {
  43752. return false;
  43753. }
  43754. }
  43755. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43756. mesh.createNormals(true);
  43757. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43758. }
  43759. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43760. if (effect) {
  43761. scene.resetCachedMaterial();
  43762. subMesh.setEffect(effect, defines);
  43763. this.buildUniformLayout();
  43764. }
  43765. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43766. return false;
  43767. }
  43768. defines._renderId = scene.getRenderId();
  43769. this._wasPreviouslyReady = true;
  43770. return true;
  43771. };
  43772. /**
  43773. * Specifies if the material uses metallic roughness workflow.
  43774. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43775. */
  43776. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43777. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43778. return true;
  43779. }
  43780. return false;
  43781. };
  43782. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43783. if (onCompiled === void 0) { onCompiled = null; }
  43784. if (onError === void 0) { onError = null; }
  43785. if (useInstances === void 0) { useInstances = null; }
  43786. if (useClipPlane === void 0) { useClipPlane = null; }
  43787. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43788. if (!defines.isDirty) {
  43789. return null;
  43790. }
  43791. defines.markAsProcessed();
  43792. var scene = this.getScene();
  43793. var engine = scene.getEngine();
  43794. // Fallbacks
  43795. var fallbacks = new BABYLON.EffectFallbacks();
  43796. var fallbackRank = 0;
  43797. if (defines.USESPHERICALINVERTEX) {
  43798. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43799. }
  43800. if (defines.FOG) {
  43801. fallbacks.addFallback(fallbackRank, "FOG");
  43802. }
  43803. if (defines.SPECULARAA) {
  43804. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43805. }
  43806. if (defines.POINTSIZE) {
  43807. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43808. }
  43809. if (defines.LOGARITHMICDEPTH) {
  43810. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43811. }
  43812. if (defines.PARALLAX) {
  43813. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43814. }
  43815. if (defines.PARALLAXOCCLUSION) {
  43816. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43817. }
  43818. if (defines.ENVIRONMENTBRDF) {
  43819. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43820. }
  43821. if (defines.TANGENT) {
  43822. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43823. }
  43824. if (defines.BUMP) {
  43825. fallbacks.addFallback(fallbackRank++, "BUMP");
  43826. }
  43827. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43828. if (defines.SPECULARTERM) {
  43829. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43830. }
  43831. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43832. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43833. }
  43834. if (defines.LIGHTMAP) {
  43835. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43836. }
  43837. if (defines.NORMAL) {
  43838. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43839. }
  43840. if (defines.AMBIENT) {
  43841. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43842. }
  43843. if (defines.EMISSIVE) {
  43844. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43845. }
  43846. if (defines.VERTEXCOLOR) {
  43847. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43848. }
  43849. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43850. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43851. }
  43852. if (defines.MORPHTARGETS) {
  43853. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43854. }
  43855. //Attributes
  43856. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43857. if (defines.NORMAL) {
  43858. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43859. }
  43860. if (defines.TANGENT) {
  43861. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43862. }
  43863. if (defines.UV1) {
  43864. attribs.push(BABYLON.VertexBuffer.UVKind);
  43865. }
  43866. if (defines.UV2) {
  43867. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43868. }
  43869. if (defines.VERTEXCOLOR) {
  43870. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43871. }
  43872. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43873. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43874. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43875. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43876. "vFogInfos", "vFogColor", "pointSize",
  43877. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43878. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43879. "mBones",
  43880. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43881. "vLightingIntensity",
  43882. "logarithmicDepthConstant",
  43883. "vSphericalX", "vSphericalY", "vSphericalZ",
  43884. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43885. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43886. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43887. "vTangentSpaceParams"
  43888. ];
  43889. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43890. "bumpSampler", "lightmapSampler", "opacitySampler",
  43891. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43892. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43893. "microSurfaceSampler", "environmentBrdfSampler"];
  43894. var uniformBuffers = ["Material", "Scene"];
  43895. if (BABYLON.ImageProcessingConfiguration) {
  43896. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43897. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43898. }
  43899. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43900. uniformsNames: uniforms,
  43901. uniformBuffersNames: uniformBuffers,
  43902. samplers: samplers,
  43903. defines: defines,
  43904. maxSimultaneousLights: this._maxSimultaneousLights
  43905. });
  43906. var join = defines.toString();
  43907. return engine.createEffect("pbr", {
  43908. attributes: attribs,
  43909. uniformsNames: uniforms,
  43910. uniformBuffersNames: uniformBuffers,
  43911. samplers: samplers,
  43912. defines: join,
  43913. fallbacks: fallbacks,
  43914. onCompiled: onCompiled,
  43915. onError: onError,
  43916. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43917. }, engine);
  43918. };
  43919. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43920. if (useInstances === void 0) { useInstances = null; }
  43921. if (useClipPlane === void 0) { useClipPlane = null; }
  43922. var scene = this.getScene();
  43923. var engine = scene.getEngine();
  43924. // Lights
  43925. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43926. defines._needNormals = true;
  43927. // Textures
  43928. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43929. if (defines._areTexturesDirty) {
  43930. defines._needUVs = false;
  43931. if (scene.texturesEnabled) {
  43932. if (scene.getEngine().getCaps().textureLOD) {
  43933. defines.LODBASEDMICROSFURACE = true;
  43934. }
  43935. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43936. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43937. }
  43938. else {
  43939. defines.ALBEDO = false;
  43940. }
  43941. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43942. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43943. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43944. }
  43945. else {
  43946. defines.AMBIENT = false;
  43947. }
  43948. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43949. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43950. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43951. }
  43952. else {
  43953. defines.OPACITY = false;
  43954. }
  43955. var reflectionTexture = this._getReflectionTexture();
  43956. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43957. defines.REFLECTION = true;
  43958. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43959. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43960. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43961. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43962. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43963. defines.INVERTCUBICMAP = true;
  43964. }
  43965. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43966. switch (reflectionTexture.coordinatesMode) {
  43967. case BABYLON.Texture.EXPLICIT_MODE:
  43968. defines.REFLECTIONMAP_EXPLICIT = true;
  43969. break;
  43970. case BABYLON.Texture.PLANAR_MODE:
  43971. defines.REFLECTIONMAP_PLANAR = true;
  43972. break;
  43973. case BABYLON.Texture.PROJECTION_MODE:
  43974. defines.REFLECTIONMAP_PROJECTION = true;
  43975. break;
  43976. case BABYLON.Texture.SKYBOX_MODE:
  43977. defines.REFLECTIONMAP_SKYBOX = true;
  43978. break;
  43979. case BABYLON.Texture.SPHERICAL_MODE:
  43980. defines.REFLECTIONMAP_SPHERICAL = true;
  43981. break;
  43982. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43983. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43984. break;
  43985. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43986. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43987. break;
  43988. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43989. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43990. break;
  43991. case BABYLON.Texture.CUBIC_MODE:
  43992. case BABYLON.Texture.INVCUBIC_MODE:
  43993. default:
  43994. defines.REFLECTIONMAP_CUBIC = true;
  43995. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43996. break;
  43997. }
  43998. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43999. if (reflectionTexture.sphericalPolynomial) {
  44000. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44001. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44002. defines.USESPHERICALINVERTEX = false;
  44003. }
  44004. else {
  44005. defines.USESPHERICALINVERTEX = true;
  44006. }
  44007. }
  44008. }
  44009. }
  44010. else {
  44011. defines.REFLECTION = false;
  44012. defines.REFLECTIONMAP_3D = false;
  44013. defines.REFLECTIONMAP_SPHERICAL = false;
  44014. defines.REFLECTIONMAP_PLANAR = false;
  44015. defines.REFLECTIONMAP_CUBIC = false;
  44016. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44017. defines.REFLECTIONMAP_PROJECTION = false;
  44018. defines.REFLECTIONMAP_SKYBOX = false;
  44019. defines.REFLECTIONMAP_EXPLICIT = false;
  44020. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44021. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44022. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44023. defines.INVERTCUBICMAP = false;
  44024. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44025. defines.USESPHERICALINVERTEX = false;
  44026. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44027. defines.LODINREFLECTIONALPHA = false;
  44028. defines.GAMMAREFLECTION = false;
  44029. defines.RGBDREFLECTION = false;
  44030. }
  44031. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44032. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44033. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44034. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44035. }
  44036. else {
  44037. defines.LIGHTMAP = false;
  44038. }
  44039. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44040. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44041. }
  44042. else {
  44043. defines.EMISSIVE = false;
  44044. }
  44045. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44046. if (this._metallicTexture) {
  44047. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44048. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44049. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44050. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44051. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44052. }
  44053. else if (this._reflectivityTexture) {
  44054. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44055. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44056. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44057. }
  44058. else {
  44059. defines.REFLECTIVITY = false;
  44060. }
  44061. if (this._microSurfaceTexture) {
  44062. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44063. }
  44064. else {
  44065. defines.MICROSURFACEMAP = false;
  44066. }
  44067. }
  44068. else {
  44069. defines.REFLECTIVITY = false;
  44070. defines.MICROSURFACEMAP = false;
  44071. }
  44072. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44073. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44074. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44075. defines.PARALLAX = true;
  44076. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44077. }
  44078. else {
  44079. defines.PARALLAX = false;
  44080. }
  44081. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44082. }
  44083. else {
  44084. defines.BUMP = false;
  44085. }
  44086. var refractionTexture = this._getRefractionTexture();
  44087. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44088. defines.REFRACTION = true;
  44089. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44090. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44091. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44092. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44093. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44094. if (this._linkRefractionWithTransparency) {
  44095. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44096. }
  44097. }
  44098. else {
  44099. defines.REFRACTION = false;
  44100. }
  44101. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44102. defines.ENVIRONMENTBRDF = true;
  44103. }
  44104. else {
  44105. defines.ENVIRONMENTBRDF = false;
  44106. }
  44107. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44108. defines.ALPHAFROMALBEDO = true;
  44109. }
  44110. else {
  44111. defines.ALPHAFROMALBEDO = false;
  44112. }
  44113. }
  44114. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44115. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44116. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44117. if (!this.backFaceCulling && this._twoSidedLighting) {
  44118. defines.TWOSIDEDLIGHTING = true;
  44119. }
  44120. else {
  44121. defines.TWOSIDEDLIGHTING = false;
  44122. }
  44123. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44124. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44125. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44126. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44127. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44128. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44129. }
  44130. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44131. this._imageProcessingConfiguration.prepareDefines(defines);
  44132. }
  44133. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44134. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44135. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44136. // Misc.
  44137. if (defines._areMiscDirty) {
  44138. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44139. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44140. }
  44141. // Values that need to be evaluated on every frame
  44142. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44143. // Attribs
  44144. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44145. };
  44146. /**
  44147. * Force shader compilation
  44148. */
  44149. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44150. var _this = this;
  44151. var localOptions = __assign({ clipPlane: false }, options);
  44152. var defines = new PBRMaterialDefines();
  44153. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44154. if (effect.isReady()) {
  44155. if (onCompiled) {
  44156. onCompiled(this);
  44157. }
  44158. }
  44159. else {
  44160. effect.onCompileObservable.add(function () {
  44161. if (onCompiled) {
  44162. onCompiled(_this);
  44163. }
  44164. });
  44165. }
  44166. };
  44167. /**
  44168. * Initializes the uniform buffer layout for the shader.
  44169. */
  44170. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44171. // Order is important !
  44172. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44173. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44174. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44175. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44176. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44177. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44178. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44179. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44180. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44181. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44182. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44183. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44184. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44185. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44186. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44187. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44188. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44189. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44190. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44191. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44192. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44193. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44194. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44195. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44196. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44197. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44198. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44199. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44200. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44201. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44202. this._uniformBuffer.addUniform("pointSize", 1);
  44203. this._uniformBuffer.create();
  44204. };
  44205. /**
  44206. * Unbinds the textures.
  44207. */
  44208. PBRBaseMaterial.prototype.unbind = function () {
  44209. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44210. this._uniformBuffer.setTexture("reflectionSampler", null);
  44211. }
  44212. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44213. this._uniformBuffer.setTexture("refractionSampler", null);
  44214. }
  44215. _super.prototype.unbind.call(this);
  44216. };
  44217. /**
  44218. * Binds the submesh data.
  44219. * @param world - The world matrix.
  44220. * @param mesh - The BJS mesh.
  44221. * @param subMesh - A submesh of the BJS mesh.
  44222. */
  44223. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44224. var scene = this.getScene();
  44225. var defines = subMesh._materialDefines;
  44226. if (!defines) {
  44227. return;
  44228. }
  44229. var effect = subMesh.effect;
  44230. if (!effect) {
  44231. return;
  44232. }
  44233. this._activeEffect = effect;
  44234. // Matrices
  44235. this.bindOnlyWorldMatrix(world);
  44236. // Normal Matrix
  44237. if (defines.OBJECTSPACE_NORMALMAP) {
  44238. world.toNormalMatrix(this._normalMatrix);
  44239. this.bindOnlyNormalMatrix(this._normalMatrix);
  44240. }
  44241. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44242. // Bones
  44243. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44244. var reflectionTexture = null;
  44245. if (mustRebind) {
  44246. this._uniformBuffer.bindToEffect(effect, "Material");
  44247. this.bindViewProjection(effect);
  44248. reflectionTexture = this._getReflectionTexture();
  44249. var refractionTexture = this._getRefractionTexture();
  44250. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44251. // Texture uniforms
  44252. if (scene.texturesEnabled) {
  44253. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44254. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44255. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44256. }
  44257. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44258. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44259. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44260. }
  44261. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44262. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44263. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44264. }
  44265. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44266. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44267. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44268. if (reflectionTexture.boundingBoxSize) {
  44269. var cubeTexture = reflectionTexture;
  44270. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44271. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44272. }
  44273. var polynomials = reflectionTexture.sphericalPolynomial;
  44274. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44275. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44276. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44277. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44278. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44279. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44280. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44281. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44282. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44283. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44284. }
  44285. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44286. }
  44287. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44288. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44289. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44290. }
  44291. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44292. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44293. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44294. }
  44295. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44296. if (this._metallicTexture) {
  44297. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44298. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44299. }
  44300. else if (this._reflectivityTexture) {
  44301. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44302. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44303. }
  44304. if (this._microSurfaceTexture) {
  44305. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44306. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44307. }
  44308. }
  44309. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44310. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44311. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44312. if (scene._mirroredCameraPosition) {
  44313. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44314. }
  44315. else {
  44316. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44317. }
  44318. }
  44319. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44320. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44321. var depth = 1.0;
  44322. if (!refractionTexture.isCube) {
  44323. if (refractionTexture.depth) {
  44324. depth = refractionTexture.depth;
  44325. }
  44326. }
  44327. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44328. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44329. }
  44330. }
  44331. // Point size
  44332. if (this.pointsCloud) {
  44333. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44334. }
  44335. // Colors
  44336. if (defines.METALLICWORKFLOW) {
  44337. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44338. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44339. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44340. }
  44341. else {
  44342. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44343. }
  44344. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44345. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44346. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44347. // Misc
  44348. this._lightingInfos.x = this._directIntensity;
  44349. this._lightingInfos.y = this._emissiveIntensity;
  44350. this._lightingInfos.z = this._environmentIntensity;
  44351. this._lightingInfos.w = this._specularIntensity;
  44352. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44353. }
  44354. // Textures
  44355. if (scene.texturesEnabled) {
  44356. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44357. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44358. }
  44359. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44360. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44361. }
  44362. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44363. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44364. }
  44365. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44366. if (defines.LODBASEDMICROSFURACE) {
  44367. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44368. }
  44369. else {
  44370. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44371. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44372. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44373. }
  44374. }
  44375. if (defines.ENVIRONMENTBRDF) {
  44376. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44377. }
  44378. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44379. if (defines.LODBASEDMICROSFURACE) {
  44380. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44381. }
  44382. else {
  44383. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44384. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44385. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44386. }
  44387. }
  44388. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44389. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44390. }
  44391. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44392. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44393. }
  44394. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44395. if (this._metallicTexture) {
  44396. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44397. }
  44398. else if (this._reflectivityTexture) {
  44399. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44400. }
  44401. if (this._microSurfaceTexture) {
  44402. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44403. }
  44404. }
  44405. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44406. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44407. }
  44408. }
  44409. // Clip plane
  44410. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44411. // Colors
  44412. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44413. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44414. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44415. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44416. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44417. }
  44418. if (mustRebind || !this.isFrozen) {
  44419. // Lights
  44420. if (scene.lightsEnabled && !this._disableLighting) {
  44421. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44422. }
  44423. // View
  44424. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44425. this.bindView(effect);
  44426. }
  44427. // Fog
  44428. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44429. // Morph targets
  44430. if (defines.NUM_MORPH_INFLUENCERS) {
  44431. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44432. }
  44433. // image processing
  44434. this._imageProcessingConfiguration.bind(this._activeEffect);
  44435. // Log. depth
  44436. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44437. }
  44438. this._uniformBuffer.update();
  44439. this._afterBind(mesh, this._activeEffect);
  44440. };
  44441. /**
  44442. * Returns the animatable textures.
  44443. * @returns - Array of animatable textures.
  44444. */
  44445. PBRBaseMaterial.prototype.getAnimatables = function () {
  44446. var results = [];
  44447. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44448. results.push(this._albedoTexture);
  44449. }
  44450. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44451. results.push(this._ambientTexture);
  44452. }
  44453. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44454. results.push(this._opacityTexture);
  44455. }
  44456. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44457. results.push(this._reflectionTexture);
  44458. }
  44459. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44460. results.push(this._emissiveTexture);
  44461. }
  44462. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44463. results.push(this._metallicTexture);
  44464. }
  44465. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44466. results.push(this._reflectivityTexture);
  44467. }
  44468. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44469. results.push(this._bumpTexture);
  44470. }
  44471. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44472. results.push(this._lightmapTexture);
  44473. }
  44474. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44475. results.push(this._refractionTexture);
  44476. }
  44477. return results;
  44478. };
  44479. /**
  44480. * Returns the texture used for reflections.
  44481. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44482. */
  44483. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44484. if (this._reflectionTexture) {
  44485. return this._reflectionTexture;
  44486. }
  44487. return this.getScene().environmentTexture;
  44488. };
  44489. /**
  44490. * Returns the texture used for refraction or null if none is used.
  44491. * @returns - Refection texture if present. If no refraction texture and refraction
  44492. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44493. */
  44494. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44495. if (this._refractionTexture) {
  44496. return this._refractionTexture;
  44497. }
  44498. if (this._linkRefractionWithTransparency) {
  44499. return this.getScene().environmentTexture;
  44500. }
  44501. return null;
  44502. };
  44503. /**
  44504. * Disposes the resources of the material.
  44505. * @param forceDisposeEffect - Forces the disposal of effects.
  44506. * @param forceDisposeTextures - Forces the disposal of all textures.
  44507. */
  44508. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44509. if (forceDisposeTextures) {
  44510. if (this._albedoTexture) {
  44511. this._albedoTexture.dispose();
  44512. }
  44513. if (this._ambientTexture) {
  44514. this._ambientTexture.dispose();
  44515. }
  44516. if (this._opacityTexture) {
  44517. this._opacityTexture.dispose();
  44518. }
  44519. if (this._reflectionTexture) {
  44520. this._reflectionTexture.dispose();
  44521. }
  44522. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44523. this._environmentBRDFTexture.dispose();
  44524. }
  44525. if (this._emissiveTexture) {
  44526. this._emissiveTexture.dispose();
  44527. }
  44528. if (this._metallicTexture) {
  44529. this._metallicTexture.dispose();
  44530. }
  44531. if (this._reflectivityTexture) {
  44532. this._reflectivityTexture.dispose();
  44533. }
  44534. if (this._bumpTexture) {
  44535. this._bumpTexture.dispose();
  44536. }
  44537. if (this._lightmapTexture) {
  44538. this._lightmapTexture.dispose();
  44539. }
  44540. if (this._refractionTexture) {
  44541. this._refractionTexture.dispose();
  44542. }
  44543. }
  44544. this._renderTargets.dispose();
  44545. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44546. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44547. }
  44548. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44549. };
  44550. /**
  44551. * Stores the reflectivity values based on metallic roughness workflow.
  44552. */
  44553. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44554. __decorate([
  44555. BABYLON.serializeAsImageProcessingConfiguration()
  44556. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44557. __decorate([
  44558. BABYLON.serialize()
  44559. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44560. __decorate([
  44561. BABYLON.serialize()
  44562. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44563. return PBRBaseMaterial;
  44564. }(BABYLON.PushMaterial));
  44565. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44566. })(BABYLON || (BABYLON = {}));
  44567. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44568. var BABYLON;
  44569. (function (BABYLON) {
  44570. /**
  44571. * The Physically based simple base material of BJS.
  44572. *
  44573. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44574. * It is used as the base class for both the specGloss and metalRough conventions.
  44575. */
  44576. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44577. __extends(PBRBaseSimpleMaterial, _super);
  44578. /**
  44579. * Instantiates a new PBRMaterial instance.
  44580. *
  44581. * @param name The material name
  44582. * @param scene The scene the material will be use in.
  44583. */
  44584. function PBRBaseSimpleMaterial(name, scene) {
  44585. var _this = _super.call(this, name, scene) || this;
  44586. /**
  44587. * Number of Simultaneous lights allowed on the material.
  44588. */
  44589. _this.maxSimultaneousLights = 4;
  44590. /**
  44591. * If sets to true, disables all the lights affecting the material.
  44592. */
  44593. _this.disableLighting = false;
  44594. /**
  44595. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44596. */
  44597. _this.invertNormalMapX = false;
  44598. /**
  44599. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44600. */
  44601. _this.invertNormalMapY = false;
  44602. /**
  44603. * Emissivie color used to self-illuminate the model.
  44604. */
  44605. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44606. /**
  44607. * Occlusion Channel Strenght.
  44608. */
  44609. _this.occlusionStrength = 1.0;
  44610. _this.useLightmapAsShadowmap = false;
  44611. _this._useAlphaFromAlbedoTexture = true;
  44612. _this._useAmbientInGrayScale = true;
  44613. return _this;
  44614. }
  44615. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44616. /**
  44617. * Gets the current double sided mode.
  44618. */
  44619. get: function () {
  44620. return this._twoSidedLighting;
  44621. },
  44622. /**
  44623. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44624. */
  44625. set: function (value) {
  44626. if (this._twoSidedLighting === value) {
  44627. return;
  44628. }
  44629. this._twoSidedLighting = value;
  44630. this.backFaceCulling = !value;
  44631. this._markAllSubMeshesAsTexturesDirty();
  44632. },
  44633. enumerable: true,
  44634. configurable: true
  44635. });
  44636. /**
  44637. * Return the active textures of the material.
  44638. */
  44639. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44640. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44641. if (this.environmentTexture) {
  44642. activeTextures.push(this.environmentTexture);
  44643. }
  44644. if (this.normalTexture) {
  44645. activeTextures.push(this.normalTexture);
  44646. }
  44647. if (this.emissiveTexture) {
  44648. activeTextures.push(this.emissiveTexture);
  44649. }
  44650. if (this.occlusionTexture) {
  44651. activeTextures.push(this.occlusionTexture);
  44652. }
  44653. if (this.lightmapTexture) {
  44654. activeTextures.push(this.lightmapTexture);
  44655. }
  44656. return activeTextures;
  44657. };
  44658. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44659. if (_super.prototype.hasTexture.call(this, texture)) {
  44660. return true;
  44661. }
  44662. if (this.lightmapTexture === texture) {
  44663. return true;
  44664. }
  44665. return false;
  44666. };
  44667. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44668. return "PBRBaseSimpleMaterial";
  44669. };
  44670. __decorate([
  44671. BABYLON.serialize(),
  44672. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44673. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44674. __decorate([
  44675. BABYLON.serialize(),
  44676. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44677. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44678. __decorate([
  44679. BABYLON.serializeAsTexture(),
  44680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44681. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44682. __decorate([
  44683. BABYLON.serialize(),
  44684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44685. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44686. __decorate([
  44687. BABYLON.serialize(),
  44688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44689. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44690. __decorate([
  44691. BABYLON.serializeAsTexture(),
  44692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44693. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44694. __decorate([
  44695. BABYLON.serializeAsColor3("emissive"),
  44696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44697. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44698. __decorate([
  44699. BABYLON.serializeAsTexture(),
  44700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44701. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44702. __decorate([
  44703. BABYLON.serialize(),
  44704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44705. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44706. __decorate([
  44707. BABYLON.serializeAsTexture(),
  44708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44709. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44710. __decorate([
  44711. BABYLON.serialize(),
  44712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44713. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44714. __decorate([
  44715. BABYLON.serialize()
  44716. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44717. __decorate([
  44718. BABYLON.serializeAsTexture(),
  44719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44720. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44721. __decorate([
  44722. BABYLON.serialize(),
  44723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44724. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44725. return PBRBaseSimpleMaterial;
  44726. }(BABYLON.PBRBaseMaterial));
  44727. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44728. })(BABYLON || (BABYLON = {}));
  44729. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44730. var BABYLON;
  44731. (function (BABYLON) {
  44732. /**
  44733. * The Physically based material of BJS.
  44734. *
  44735. * This offers the main features of a standard PBR material.
  44736. * For more information, please refer to the documentation :
  44737. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44738. */
  44739. var PBRMaterial = /** @class */ (function (_super) {
  44740. __extends(PBRMaterial, _super);
  44741. /**
  44742. * Instantiates a new PBRMaterial instance.
  44743. *
  44744. * @param name The material name
  44745. * @param scene The scene the material will be use in.
  44746. */
  44747. function PBRMaterial(name, scene) {
  44748. var _this = _super.call(this, name, scene) || this;
  44749. /**
  44750. * Intensity of the direct lights e.g. the four lights available in your scene.
  44751. * This impacts both the direct diffuse and specular highlights.
  44752. */
  44753. _this.directIntensity = 1.0;
  44754. /**
  44755. * Intensity of the emissive part of the material.
  44756. * This helps controlling the emissive effect without modifying the emissive color.
  44757. */
  44758. _this.emissiveIntensity = 1.0;
  44759. /**
  44760. * Intensity of the environment e.g. how much the environment will light the object
  44761. * either through harmonics for rough material or through the refelction for shiny ones.
  44762. */
  44763. _this.environmentIntensity = 1.0;
  44764. /**
  44765. * This is a special control allowing the reduction of the specular highlights coming from the
  44766. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44767. */
  44768. _this.specularIntensity = 1.0;
  44769. /**
  44770. * Debug Control allowing disabling the bump map on this material.
  44771. */
  44772. _this.disableBumpMap = false;
  44773. /**
  44774. * AKA Occlusion Texture Intensity in other nomenclature.
  44775. */
  44776. _this.ambientTextureStrength = 1.0;
  44777. /**
  44778. * The color of a material in ambient lighting.
  44779. */
  44780. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44781. /**
  44782. * AKA Diffuse Color in other nomenclature.
  44783. */
  44784. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44785. /**
  44786. * AKA Specular Color in other nomenclature.
  44787. */
  44788. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44789. /**
  44790. * The color reflected from the material.
  44791. */
  44792. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44793. /**
  44794. * The color emitted from the material.
  44795. */
  44796. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44797. /**
  44798. * AKA Glossiness in other nomenclature.
  44799. */
  44800. _this.microSurface = 1.0;
  44801. /**
  44802. * source material index of refraction (IOR)' / 'destination material IOR.
  44803. */
  44804. _this.indexOfRefraction = 0.66;
  44805. /**
  44806. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44807. */
  44808. _this.invertRefractionY = false;
  44809. /**
  44810. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44811. * Materials half opaque for instance using refraction could benefit from this control.
  44812. */
  44813. _this.linkRefractionWithTransparency = false;
  44814. _this.useLightmapAsShadowmap = false;
  44815. /**
  44816. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44817. */
  44818. _this.useAlphaFromAlbedoTexture = false;
  44819. /**
  44820. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44821. */
  44822. _this.forceAlphaTest = false;
  44823. /**
  44824. * Defines the alpha limits in alpha test mode.
  44825. */
  44826. _this.alphaCutOff = 0.4;
  44827. /**
  44828. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44829. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44830. */
  44831. _this.useSpecularOverAlpha = true;
  44832. /**
  44833. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44834. */
  44835. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44836. /**
  44837. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44838. */
  44839. _this.useRoughnessFromMetallicTextureAlpha = true;
  44840. /**
  44841. * Specifies if the metallic texture contains the roughness information in its green channel.
  44842. */
  44843. _this.useRoughnessFromMetallicTextureGreen = false;
  44844. /**
  44845. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44846. */
  44847. _this.useMetallnessFromMetallicTextureBlue = false;
  44848. /**
  44849. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44850. */
  44851. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44852. /**
  44853. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44854. */
  44855. _this.useAmbientInGrayScale = false;
  44856. /**
  44857. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44858. * The material will try to infer what glossiness each pixel should be.
  44859. */
  44860. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44861. /**
  44862. * BJS is using an harcoded light falloff based on a manually sets up range.
  44863. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44864. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44865. */
  44866. _this.usePhysicalLightFalloff = true;
  44867. /**
  44868. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44869. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44870. */
  44871. _this.useRadianceOverAlpha = true;
  44872. /**
  44873. * Allows using an object space normal map (instead of tangent space).
  44874. */
  44875. _this.useObjectSpaceNormalMap = false;
  44876. /**
  44877. * Allows using the bump map in parallax mode.
  44878. */
  44879. _this.useParallax = false;
  44880. /**
  44881. * Allows using the bump map in parallax occlusion mode.
  44882. */
  44883. _this.useParallaxOcclusion = false;
  44884. /**
  44885. * Controls the scale bias of the parallax mode.
  44886. */
  44887. _this.parallaxScaleBias = 0.05;
  44888. /**
  44889. * If sets to true, disables all the lights affecting the material.
  44890. */
  44891. _this.disableLighting = false;
  44892. /**
  44893. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44894. */
  44895. _this.forceIrradianceInFragment = false;
  44896. /**
  44897. * Number of Simultaneous lights allowed on the material.
  44898. */
  44899. _this.maxSimultaneousLights = 4;
  44900. /**
  44901. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44902. */
  44903. _this.invertNormalMapX = false;
  44904. /**
  44905. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44906. */
  44907. _this.invertNormalMapY = false;
  44908. /**
  44909. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44910. */
  44911. _this.twoSidedLighting = false;
  44912. /**
  44913. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44914. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44915. */
  44916. _this.useAlphaFresnel = false;
  44917. /**
  44918. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44919. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44920. */
  44921. _this.useLinearAlphaFresnel = false;
  44922. /**
  44923. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44924. * And/Or occlude the blended part.
  44925. */
  44926. _this.environmentBRDFTexture = null;
  44927. /**
  44928. * Force normal to face away from face.
  44929. */
  44930. _this.forceNormalForward = false;
  44931. /**
  44932. * Enables specular anti aliasing in the PBR shader.
  44933. * It will both interacts on the Geometry for analytical and IBL lighting.
  44934. * It also prefilter the roughness map based on the bump values.
  44935. */
  44936. _this.enableSpecularAntiAliasing = false;
  44937. /**
  44938. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44939. * makes the reflect vector face the model (under horizon).
  44940. */
  44941. _this.useHorizonOcclusion = true;
  44942. /**
  44943. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44944. * too much the area relying on ambient texture to define their ambient occlusion.
  44945. */
  44946. _this.useRadianceOcclusion = true;
  44947. /**
  44948. * If set to true, no lighting calculations will be applied.
  44949. */
  44950. _this.unlit = false;
  44951. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44952. return _this;
  44953. }
  44954. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44955. /**
  44956. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44957. */
  44958. get: function () {
  44959. return this._PBRMATERIAL_OPAQUE;
  44960. },
  44961. enumerable: true,
  44962. configurable: true
  44963. });
  44964. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44965. /**
  44966. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44967. */
  44968. get: function () {
  44969. return this._PBRMATERIAL_ALPHATEST;
  44970. },
  44971. enumerable: true,
  44972. configurable: true
  44973. });
  44974. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44975. /**
  44976. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44977. */
  44978. get: function () {
  44979. return this._PBRMATERIAL_ALPHABLEND;
  44980. },
  44981. enumerable: true,
  44982. configurable: true
  44983. });
  44984. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44985. /**
  44986. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44987. * They are also discarded below the alpha cutoff threshold to improve performances.
  44988. */
  44989. get: function () {
  44990. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44991. },
  44992. enumerable: true,
  44993. configurable: true
  44994. });
  44995. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44996. /**
  44997. * Gets the image processing configuration used either in this material.
  44998. */
  44999. get: function () {
  45000. return this._imageProcessingConfiguration;
  45001. },
  45002. /**
  45003. * Sets the Default image processing configuration used either in the this material.
  45004. *
  45005. * If sets to null, the scene one is in use.
  45006. */
  45007. set: function (value) {
  45008. this._attachImageProcessingConfiguration(value);
  45009. // Ensure the effect will be rebuilt.
  45010. this._markAllSubMeshesAsTexturesDirty();
  45011. },
  45012. enumerable: true,
  45013. configurable: true
  45014. });
  45015. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45016. /**
  45017. * Gets wether the color curves effect is enabled.
  45018. */
  45019. get: function () {
  45020. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45021. },
  45022. /**
  45023. * Sets wether the color curves effect is enabled.
  45024. */
  45025. set: function (value) {
  45026. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45027. },
  45028. enumerable: true,
  45029. configurable: true
  45030. });
  45031. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45032. /**
  45033. * Gets wether the color grading effect is enabled.
  45034. */
  45035. get: function () {
  45036. return this.imageProcessingConfiguration.colorGradingEnabled;
  45037. },
  45038. /**
  45039. * Gets wether the color grading effect is enabled.
  45040. */
  45041. set: function (value) {
  45042. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45043. },
  45044. enumerable: true,
  45045. configurable: true
  45046. });
  45047. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45048. /**
  45049. * Gets wether tonemapping is enabled or not.
  45050. */
  45051. get: function () {
  45052. return this._imageProcessingConfiguration.toneMappingEnabled;
  45053. },
  45054. /**
  45055. * Sets wether tonemapping is enabled or not
  45056. */
  45057. set: function (value) {
  45058. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45059. },
  45060. enumerable: true,
  45061. configurable: true
  45062. });
  45063. ;
  45064. ;
  45065. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45066. /**
  45067. * The camera exposure used on this material.
  45068. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45069. * This corresponds to a photographic exposure.
  45070. */
  45071. get: function () {
  45072. return this._imageProcessingConfiguration.exposure;
  45073. },
  45074. /**
  45075. * The camera exposure used on this material.
  45076. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45077. * This corresponds to a photographic exposure.
  45078. */
  45079. set: function (value) {
  45080. this._imageProcessingConfiguration.exposure = value;
  45081. },
  45082. enumerable: true,
  45083. configurable: true
  45084. });
  45085. ;
  45086. ;
  45087. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45088. /**
  45089. * Gets The camera contrast used on this material.
  45090. */
  45091. get: function () {
  45092. return this._imageProcessingConfiguration.contrast;
  45093. },
  45094. /**
  45095. * Sets The camera contrast used on this material.
  45096. */
  45097. set: function (value) {
  45098. this._imageProcessingConfiguration.contrast = value;
  45099. },
  45100. enumerable: true,
  45101. configurable: true
  45102. });
  45103. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45104. /**
  45105. * Gets the Color Grading 2D Lookup Texture.
  45106. */
  45107. get: function () {
  45108. return this._imageProcessingConfiguration.colorGradingTexture;
  45109. },
  45110. /**
  45111. * Sets the Color Grading 2D Lookup Texture.
  45112. */
  45113. set: function (value) {
  45114. this._imageProcessingConfiguration.colorGradingTexture = value;
  45115. },
  45116. enumerable: true,
  45117. configurable: true
  45118. });
  45119. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45120. /**
  45121. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45122. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45123. * 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;
  45124. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45125. */
  45126. get: function () {
  45127. return this._imageProcessingConfiguration.colorCurves;
  45128. },
  45129. /**
  45130. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45131. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45132. * 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;
  45133. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45134. */
  45135. set: function (value) {
  45136. this._imageProcessingConfiguration.colorCurves = value;
  45137. },
  45138. enumerable: true,
  45139. configurable: true
  45140. });
  45141. /**
  45142. * Returns the name of this material class.
  45143. */
  45144. PBRMaterial.prototype.getClassName = function () {
  45145. return "PBRMaterial";
  45146. };
  45147. /**
  45148. * Returns an array of the actively used textures.
  45149. * @returns - Array of BaseTextures
  45150. */
  45151. PBRMaterial.prototype.getActiveTextures = function () {
  45152. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45153. if (this._albedoTexture) {
  45154. activeTextures.push(this._albedoTexture);
  45155. }
  45156. if (this._ambientTexture) {
  45157. activeTextures.push(this._ambientTexture);
  45158. }
  45159. if (this._opacityTexture) {
  45160. activeTextures.push(this._opacityTexture);
  45161. }
  45162. if (this._reflectionTexture) {
  45163. activeTextures.push(this._reflectionTexture);
  45164. }
  45165. if (this._emissiveTexture) {
  45166. activeTextures.push(this._emissiveTexture);
  45167. }
  45168. if (this._reflectivityTexture) {
  45169. activeTextures.push(this._reflectivityTexture);
  45170. }
  45171. if (this._metallicTexture) {
  45172. activeTextures.push(this._metallicTexture);
  45173. }
  45174. if (this._microSurfaceTexture) {
  45175. activeTextures.push(this._microSurfaceTexture);
  45176. }
  45177. if (this._bumpTexture) {
  45178. activeTextures.push(this._bumpTexture);
  45179. }
  45180. if (this._lightmapTexture) {
  45181. activeTextures.push(this._lightmapTexture);
  45182. }
  45183. if (this._refractionTexture) {
  45184. activeTextures.push(this._refractionTexture);
  45185. }
  45186. return activeTextures;
  45187. };
  45188. /**
  45189. * Checks to see if a texture is used in the material.
  45190. * @param texture - Base texture to use.
  45191. * @returns - Boolean specifying if a texture is used in the material.
  45192. */
  45193. PBRMaterial.prototype.hasTexture = function (texture) {
  45194. if (_super.prototype.hasTexture.call(this, texture)) {
  45195. return true;
  45196. }
  45197. if (this._albedoTexture === texture) {
  45198. return true;
  45199. }
  45200. if (this._ambientTexture === texture) {
  45201. return true;
  45202. }
  45203. if (this._opacityTexture === texture) {
  45204. return true;
  45205. }
  45206. if (this._reflectionTexture === texture) {
  45207. return true;
  45208. }
  45209. if (this._reflectivityTexture === texture) {
  45210. return true;
  45211. }
  45212. if (this._metallicTexture === texture) {
  45213. return true;
  45214. }
  45215. if (this._microSurfaceTexture === texture) {
  45216. return true;
  45217. }
  45218. if (this._bumpTexture === texture) {
  45219. return true;
  45220. }
  45221. if (this._lightmapTexture === texture) {
  45222. return true;
  45223. }
  45224. if (this._refractionTexture === texture) {
  45225. return true;
  45226. }
  45227. return false;
  45228. };
  45229. /**
  45230. * Makes a duplicate of the current material.
  45231. * @param name - name to use for the new material.
  45232. */
  45233. PBRMaterial.prototype.clone = function (name) {
  45234. var _this = this;
  45235. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45236. clone.id = name;
  45237. clone.name = name;
  45238. return clone;
  45239. };
  45240. /**
  45241. * Serializes this PBR Material.
  45242. * @returns - An object with the serialized material.
  45243. */
  45244. PBRMaterial.prototype.serialize = function () {
  45245. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45246. serializationObject.customType = "BABYLON.PBRMaterial";
  45247. return serializationObject;
  45248. };
  45249. // Statics
  45250. /**
  45251. * Parses a PBR Material from a serialized object.
  45252. * @param source - Serialized object.
  45253. * @param scene - BJS scene instance.
  45254. * @param rootUrl - url for the scene object
  45255. * @returns - PBRMaterial
  45256. */
  45257. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45258. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45259. };
  45260. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45261. /**
  45262. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45263. */
  45264. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45265. /**
  45266. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45267. */
  45268. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45269. /**
  45270. * 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.
  45271. * They are also discarded below the alpha cutoff threshold to improve performances.
  45272. */
  45273. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45274. __decorate([
  45275. BABYLON.serialize(),
  45276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45277. ], PBRMaterial.prototype, "directIntensity", void 0);
  45278. __decorate([
  45279. BABYLON.serialize(),
  45280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45281. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45282. __decorate([
  45283. BABYLON.serialize(),
  45284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45285. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45286. __decorate([
  45287. BABYLON.serialize(),
  45288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45289. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45290. __decorate([
  45291. BABYLON.serialize(),
  45292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45293. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45294. __decorate([
  45295. BABYLON.serializeAsTexture(),
  45296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45297. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45298. __decorate([
  45299. BABYLON.serializeAsTexture(),
  45300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45301. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45302. __decorate([
  45303. BABYLON.serialize(),
  45304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45305. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45306. __decorate([
  45307. BABYLON.serializeAsTexture(),
  45308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45309. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45310. __decorate([
  45311. BABYLON.serializeAsTexture(),
  45312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45313. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45314. __decorate([
  45315. BABYLON.serializeAsTexture(),
  45316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45317. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45318. __decorate([
  45319. BABYLON.serializeAsTexture(),
  45320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45321. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45322. __decorate([
  45323. BABYLON.serializeAsTexture(),
  45324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45325. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45326. __decorate([
  45327. BABYLON.serialize(),
  45328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45329. ], PBRMaterial.prototype, "metallic", void 0);
  45330. __decorate([
  45331. BABYLON.serialize(),
  45332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45333. ], PBRMaterial.prototype, "roughness", void 0);
  45334. __decorate([
  45335. BABYLON.serializeAsTexture(),
  45336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45337. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45338. __decorate([
  45339. BABYLON.serializeAsTexture(),
  45340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45341. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45342. __decorate([
  45343. BABYLON.serializeAsTexture(),
  45344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45345. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45346. __decorate([
  45347. BABYLON.serializeAsTexture(),
  45348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45349. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45350. __decorate([
  45351. BABYLON.serializeAsColor3("ambient"),
  45352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45353. ], PBRMaterial.prototype, "ambientColor", void 0);
  45354. __decorate([
  45355. BABYLON.serializeAsColor3("albedo"),
  45356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45357. ], PBRMaterial.prototype, "albedoColor", void 0);
  45358. __decorate([
  45359. BABYLON.serializeAsColor3("reflectivity"),
  45360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45361. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45362. __decorate([
  45363. BABYLON.serializeAsColor3("reflection"),
  45364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45365. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45366. __decorate([
  45367. BABYLON.serializeAsColor3("emissive"),
  45368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45369. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45370. __decorate([
  45371. BABYLON.serialize(),
  45372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45373. ], PBRMaterial.prototype, "microSurface", void 0);
  45374. __decorate([
  45375. BABYLON.serialize(),
  45376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45377. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45378. __decorate([
  45379. BABYLON.serialize(),
  45380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45381. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45382. __decorate([
  45383. BABYLON.serialize(),
  45384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45385. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45386. __decorate([
  45387. BABYLON.serialize(),
  45388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45389. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45390. __decorate([
  45391. BABYLON.serialize(),
  45392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45393. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45394. __decorate([
  45395. BABYLON.serialize(),
  45396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45397. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45398. __decorate([
  45399. BABYLON.serialize(),
  45400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45401. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45402. __decorate([
  45403. BABYLON.serialize(),
  45404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45405. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45406. __decorate([
  45407. BABYLON.serialize(),
  45408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45409. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45410. __decorate([
  45411. BABYLON.serialize(),
  45412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45413. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45414. __decorate([
  45415. BABYLON.serialize(),
  45416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45417. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45418. __decorate([
  45419. BABYLON.serialize(),
  45420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45421. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45422. __decorate([
  45423. BABYLON.serialize(),
  45424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45425. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45426. __decorate([
  45427. BABYLON.serialize(),
  45428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45429. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45430. __decorate([
  45431. BABYLON.serialize(),
  45432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45433. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45434. __decorate([
  45435. BABYLON.serialize(),
  45436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45437. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45438. __decorate([
  45439. BABYLON.serialize(),
  45440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45441. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45442. __decorate([
  45443. BABYLON.serialize(),
  45444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45445. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45446. __decorate([
  45447. BABYLON.serialize(),
  45448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45449. ], PBRMaterial.prototype, "useParallax", void 0);
  45450. __decorate([
  45451. BABYLON.serialize(),
  45452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45453. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45454. __decorate([
  45455. BABYLON.serialize(),
  45456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45457. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45458. __decorate([
  45459. BABYLON.serialize(),
  45460. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45461. ], PBRMaterial.prototype, "disableLighting", void 0);
  45462. __decorate([
  45463. BABYLON.serialize(),
  45464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45465. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45466. __decorate([
  45467. BABYLON.serialize(),
  45468. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45469. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45470. __decorate([
  45471. BABYLON.serialize(),
  45472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45473. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45474. __decorate([
  45475. BABYLON.serialize(),
  45476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45477. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45478. __decorate([
  45479. BABYLON.serialize(),
  45480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45481. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45482. __decorate([
  45483. BABYLON.serialize(),
  45484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45485. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45486. __decorate([
  45487. BABYLON.serialize(),
  45488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45489. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45490. __decorate([
  45491. BABYLON.serializeAsTexture(),
  45492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45493. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45494. __decorate([
  45495. BABYLON.serialize(),
  45496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45497. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45498. __decorate([
  45499. BABYLON.serialize(),
  45500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45501. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45502. __decorate([
  45503. BABYLON.serialize(),
  45504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45505. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45506. __decorate([
  45507. BABYLON.serialize(),
  45508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45509. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45510. __decorate([
  45511. BABYLON.serialize(),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45513. ], PBRMaterial.prototype, "unlit", void 0);
  45514. return PBRMaterial;
  45515. }(BABYLON.PBRBaseMaterial));
  45516. BABYLON.PBRMaterial = PBRMaterial;
  45517. })(BABYLON || (BABYLON = {}));
  45518. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45519. var BABYLON;
  45520. (function (BABYLON) {
  45521. /**
  45522. * The PBR material of BJS following the metal roughness convention.
  45523. *
  45524. * This fits to the PBR convention in the GLTF definition:
  45525. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45526. */
  45527. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45528. __extends(PBRMetallicRoughnessMaterial, _super);
  45529. /**
  45530. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45531. *
  45532. * @param name The material name
  45533. * @param scene The scene the material will be use in.
  45534. */
  45535. function PBRMetallicRoughnessMaterial(name, scene) {
  45536. var _this = _super.call(this, name, scene) || this;
  45537. _this._useRoughnessFromMetallicTextureAlpha = false;
  45538. _this._useRoughnessFromMetallicTextureGreen = true;
  45539. _this._useMetallnessFromMetallicTextureBlue = true;
  45540. _this.metallic = 1.0;
  45541. _this.roughness = 1.0;
  45542. return _this;
  45543. }
  45544. /**
  45545. * Return the currrent class name of the material.
  45546. */
  45547. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45548. return "PBRMetallicRoughnessMaterial";
  45549. };
  45550. /**
  45551. * Return the active textures of the material.
  45552. */
  45553. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45554. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45555. if (this.baseTexture) {
  45556. activeTextures.push(this.baseTexture);
  45557. }
  45558. if (this.metallicRoughnessTexture) {
  45559. activeTextures.push(this.metallicRoughnessTexture);
  45560. }
  45561. return activeTextures;
  45562. };
  45563. /**
  45564. * Checks to see if a texture is used in the material.
  45565. * @param texture - Base texture to use.
  45566. * @returns - Boolean specifying if a texture is used in the material.
  45567. */
  45568. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45569. if (_super.prototype.hasTexture.call(this, texture)) {
  45570. return true;
  45571. }
  45572. if (this.baseTexture === texture) {
  45573. return true;
  45574. }
  45575. if (this.metallicRoughnessTexture === texture) {
  45576. return true;
  45577. }
  45578. return false;
  45579. };
  45580. /**
  45581. * Makes a duplicate of the current material.
  45582. * @param name - name to use for the new material.
  45583. */
  45584. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45585. var _this = this;
  45586. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45587. clone.id = name;
  45588. clone.name = name;
  45589. return clone;
  45590. };
  45591. /**
  45592. * Serialize the material to a parsable JSON object.
  45593. */
  45594. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45595. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45596. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45597. return serializationObject;
  45598. };
  45599. /**
  45600. * Parses a JSON object correponding to the serialize function.
  45601. */
  45602. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45603. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45604. };
  45605. __decorate([
  45606. BABYLON.serializeAsColor3(),
  45607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45608. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45609. __decorate([
  45610. BABYLON.serializeAsTexture(),
  45611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45612. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45613. __decorate([
  45614. BABYLON.serialize(),
  45615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45616. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45617. __decorate([
  45618. BABYLON.serialize(),
  45619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45620. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45621. __decorate([
  45622. BABYLON.serializeAsTexture(),
  45623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45624. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45625. return PBRMetallicRoughnessMaterial;
  45626. }(BABYLON.PBRBaseSimpleMaterial));
  45627. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45628. })(BABYLON || (BABYLON = {}));
  45629. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45630. var BABYLON;
  45631. (function (BABYLON) {
  45632. /**
  45633. * The PBR material of BJS following the specular glossiness convention.
  45634. *
  45635. * This fits to the PBR convention in the GLTF definition:
  45636. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45637. */
  45638. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45639. __extends(PBRSpecularGlossinessMaterial, _super);
  45640. /**
  45641. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45642. *
  45643. * @param name The material name
  45644. * @param scene The scene the material will be use in.
  45645. */
  45646. function PBRSpecularGlossinessMaterial(name, scene) {
  45647. var _this = _super.call(this, name, scene) || this;
  45648. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45649. return _this;
  45650. }
  45651. /**
  45652. * Return the currrent class name of the material.
  45653. */
  45654. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45655. return "PBRSpecularGlossinessMaterial";
  45656. };
  45657. /**
  45658. * Return the active textures of the material.
  45659. */
  45660. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45661. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45662. if (this.diffuseTexture) {
  45663. activeTextures.push(this.diffuseTexture);
  45664. }
  45665. if (this.specularGlossinessTexture) {
  45666. activeTextures.push(this.specularGlossinessTexture);
  45667. }
  45668. return activeTextures;
  45669. };
  45670. /**
  45671. * Checks to see if a texture is used in the material.
  45672. * @param texture - Base texture to use.
  45673. * @returns - Boolean specifying if a texture is used in the material.
  45674. */
  45675. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45676. if (_super.prototype.hasTexture.call(this, texture)) {
  45677. return true;
  45678. }
  45679. if (this.diffuseTexture === texture) {
  45680. return true;
  45681. }
  45682. if (this.specularGlossinessTexture === texture) {
  45683. return true;
  45684. }
  45685. return false;
  45686. };
  45687. /**
  45688. * Makes a duplicate of the current material.
  45689. * @param name - name to use for the new material.
  45690. */
  45691. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45692. var _this = this;
  45693. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45694. clone.id = name;
  45695. clone.name = name;
  45696. return clone;
  45697. };
  45698. /**
  45699. * Serialize the material to a parsable JSON object.
  45700. */
  45701. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45702. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45703. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45704. return serializationObject;
  45705. };
  45706. /**
  45707. * Parses a JSON object correponding to the serialize function.
  45708. */
  45709. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45710. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45711. };
  45712. __decorate([
  45713. BABYLON.serializeAsColor3("diffuse"),
  45714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45715. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45716. __decorate([
  45717. BABYLON.serializeAsTexture(),
  45718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45719. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45720. __decorate([
  45721. BABYLON.serializeAsColor3("specular"),
  45722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45723. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45724. __decorate([
  45725. BABYLON.serialize(),
  45726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45727. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45728. __decorate([
  45729. BABYLON.serializeAsTexture(),
  45730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45731. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45732. return PBRSpecularGlossinessMaterial;
  45733. }(BABYLON.PBRBaseSimpleMaterial));
  45734. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45735. })(BABYLON || (BABYLON = {}));
  45736. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45737. var BABYLON;
  45738. (function (BABYLON) {
  45739. BABYLON.CameraInputTypes = {};
  45740. var CameraInputsManager = /** @class */ (function () {
  45741. function CameraInputsManager(camera) {
  45742. this.attached = {};
  45743. this.camera = camera;
  45744. this.checkInputs = function () { };
  45745. }
  45746. /**
  45747. * Add an input method to a camera
  45748. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45749. * @param input camera input method
  45750. */
  45751. CameraInputsManager.prototype.add = function (input) {
  45752. var type = input.getSimpleName();
  45753. if (this.attached[type]) {
  45754. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45755. return;
  45756. }
  45757. this.attached[type] = input;
  45758. input.camera = this.camera;
  45759. //for checkInputs, we are dynamically creating a function
  45760. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45761. if (input.checkInputs) {
  45762. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45763. }
  45764. if (this.attachedElement) {
  45765. input.attachControl(this.attachedElement);
  45766. }
  45767. };
  45768. /**
  45769. * Remove a specific input method from a camera
  45770. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45771. * @param inputToRemove camera input method
  45772. */
  45773. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45774. for (var cam in this.attached) {
  45775. var input = this.attached[cam];
  45776. if (input === inputToRemove) {
  45777. input.detachControl(this.attachedElement);
  45778. input.camera = null;
  45779. delete this.attached[cam];
  45780. this.rebuildInputCheck();
  45781. }
  45782. }
  45783. };
  45784. CameraInputsManager.prototype.removeByType = function (inputType) {
  45785. for (var cam in this.attached) {
  45786. var input = this.attached[cam];
  45787. if (input.getClassName() === inputType) {
  45788. input.detachControl(this.attachedElement);
  45789. input.camera = null;
  45790. delete this.attached[cam];
  45791. this.rebuildInputCheck();
  45792. }
  45793. }
  45794. };
  45795. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45796. var current = this.checkInputs;
  45797. return function () {
  45798. current();
  45799. fn();
  45800. };
  45801. };
  45802. CameraInputsManager.prototype.attachInput = function (input) {
  45803. if (this.attachedElement) {
  45804. input.attachControl(this.attachedElement, this.noPreventDefault);
  45805. }
  45806. };
  45807. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45808. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45809. if (this.attachedElement) {
  45810. return;
  45811. }
  45812. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45813. this.attachedElement = element;
  45814. this.noPreventDefault = noPreventDefault;
  45815. for (var cam in this.attached) {
  45816. this.attached[cam].attachControl(element, noPreventDefault);
  45817. }
  45818. };
  45819. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45820. if (disconnect === void 0) { disconnect = false; }
  45821. if (this.attachedElement !== element) {
  45822. return;
  45823. }
  45824. for (var cam in this.attached) {
  45825. this.attached[cam].detachControl(element);
  45826. if (disconnect) {
  45827. this.attached[cam].camera = null;
  45828. }
  45829. }
  45830. this.attachedElement = null;
  45831. };
  45832. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45833. this.checkInputs = function () { };
  45834. for (var cam in this.attached) {
  45835. var input = this.attached[cam];
  45836. if (input.checkInputs) {
  45837. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45838. }
  45839. }
  45840. };
  45841. /**
  45842. * Remove all attached input methods from a camera
  45843. */
  45844. CameraInputsManager.prototype.clear = function () {
  45845. if (this.attachedElement) {
  45846. this.detachElement(this.attachedElement, true);
  45847. }
  45848. this.attached = {};
  45849. this.attachedElement = null;
  45850. this.checkInputs = function () { };
  45851. };
  45852. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45853. var inputs = {};
  45854. for (var cam in this.attached) {
  45855. var input = this.attached[cam];
  45856. var res = BABYLON.SerializationHelper.Serialize(input);
  45857. inputs[input.getClassName()] = res;
  45858. }
  45859. serializedCamera.inputsmgr = inputs;
  45860. };
  45861. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45862. var parsedInputs = parsedCamera.inputsmgr;
  45863. if (parsedInputs) {
  45864. this.clear();
  45865. for (var n in parsedInputs) {
  45866. var construct = BABYLON.CameraInputTypes[n];
  45867. if (construct) {
  45868. var parsedinput = parsedInputs[n];
  45869. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45870. this.add(input);
  45871. }
  45872. }
  45873. }
  45874. else {
  45875. //2016-03-08 this part is for managing backward compatibility
  45876. for (var n in this.attached) {
  45877. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45878. if (construct) {
  45879. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45880. this.remove(this.attached[n]);
  45881. this.add(input);
  45882. }
  45883. }
  45884. }
  45885. };
  45886. return CameraInputsManager;
  45887. }());
  45888. BABYLON.CameraInputsManager = CameraInputsManager;
  45889. })(BABYLON || (BABYLON = {}));
  45890. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45891. var BABYLON;
  45892. (function (BABYLON) {
  45893. var TargetCamera = /** @class */ (function (_super) {
  45894. __extends(TargetCamera, _super);
  45895. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45896. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45897. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45898. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45899. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45900. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45901. _this.speed = 2.0;
  45902. _this.noRotationConstraint = false;
  45903. _this.lockedTarget = null;
  45904. _this._currentTarget = BABYLON.Vector3.Zero();
  45905. _this._viewMatrix = BABYLON.Matrix.Zero();
  45906. _this._camMatrix = BABYLON.Matrix.Zero();
  45907. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45908. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45909. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45910. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45911. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45912. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45913. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45914. return _this;
  45915. }
  45916. TargetCamera.prototype.getFrontPosition = function (distance) {
  45917. this.getWorldMatrix();
  45918. var direction = this.getTarget().subtract(this.position);
  45919. direction.normalize();
  45920. direction.scaleInPlace(distance);
  45921. return this.globalPosition.add(direction);
  45922. };
  45923. TargetCamera.prototype._getLockedTargetPosition = function () {
  45924. if (!this.lockedTarget) {
  45925. return null;
  45926. }
  45927. if (this.lockedTarget.absolutePosition) {
  45928. this.lockedTarget.computeWorldMatrix();
  45929. }
  45930. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45931. };
  45932. TargetCamera.prototype.storeState = function () {
  45933. this._storedPosition = this.position.clone();
  45934. this._storedRotation = this.rotation.clone();
  45935. if (this.rotationQuaternion) {
  45936. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45937. }
  45938. return _super.prototype.storeState.call(this);
  45939. };
  45940. /**
  45941. * Restored camera state. You must call storeState() first
  45942. */
  45943. TargetCamera.prototype._restoreStateValues = function () {
  45944. if (!_super.prototype._restoreStateValues.call(this)) {
  45945. return false;
  45946. }
  45947. this.position = this._storedPosition.clone();
  45948. this.rotation = this._storedRotation.clone();
  45949. if (this.rotationQuaternion) {
  45950. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45951. }
  45952. this.cameraDirection.copyFromFloats(0, 0, 0);
  45953. this.cameraRotation.copyFromFloats(0, 0);
  45954. return true;
  45955. };
  45956. // Cache
  45957. TargetCamera.prototype._initCache = function () {
  45958. _super.prototype._initCache.call(this);
  45959. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45960. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45961. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45962. };
  45963. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45964. if (!ignoreParentClass) {
  45965. _super.prototype._updateCache.call(this);
  45966. }
  45967. var lockedTargetPosition = this._getLockedTargetPosition();
  45968. if (!lockedTargetPosition) {
  45969. this._cache.lockedTarget = null;
  45970. }
  45971. else {
  45972. if (!this._cache.lockedTarget) {
  45973. this._cache.lockedTarget = lockedTargetPosition.clone();
  45974. }
  45975. else {
  45976. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45977. }
  45978. }
  45979. this._cache.rotation.copyFrom(this.rotation);
  45980. if (this.rotationQuaternion)
  45981. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45982. };
  45983. // Synchronized
  45984. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45985. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45986. return false;
  45987. }
  45988. var lockedTargetPosition = this._getLockedTargetPosition();
  45989. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45990. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45991. };
  45992. // Methods
  45993. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45994. var engine = this.getEngine();
  45995. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45996. };
  45997. // Target
  45998. TargetCamera.prototype.setTarget = function (target) {
  45999. this.upVector.normalize();
  46000. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46001. this._camMatrix.invert();
  46002. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46003. var vDir = target.subtract(this.position);
  46004. if (vDir.x >= 0.0) {
  46005. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46006. }
  46007. else {
  46008. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46009. }
  46010. this.rotation.z = 0;
  46011. if (isNaN(this.rotation.x)) {
  46012. this.rotation.x = 0;
  46013. }
  46014. if (isNaN(this.rotation.y)) {
  46015. this.rotation.y = 0;
  46016. }
  46017. if (isNaN(this.rotation.z)) {
  46018. this.rotation.z = 0;
  46019. }
  46020. if (this.rotationQuaternion) {
  46021. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46022. }
  46023. };
  46024. /**
  46025. * Return the current target position of the camera. This value is expressed in local space.
  46026. */
  46027. TargetCamera.prototype.getTarget = function () {
  46028. return this._currentTarget;
  46029. };
  46030. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46031. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46032. };
  46033. TargetCamera.prototype._updatePosition = function () {
  46034. if (this.parent) {
  46035. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46036. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46037. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46038. return;
  46039. }
  46040. this.position.addInPlace(this.cameraDirection);
  46041. };
  46042. TargetCamera.prototype._checkInputs = function () {
  46043. var needToMove = this._decideIfNeedsToMove();
  46044. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46045. // Move
  46046. if (needToMove) {
  46047. this._updatePosition();
  46048. }
  46049. // Rotate
  46050. if (needToRotate) {
  46051. this.rotation.x += this.cameraRotation.x;
  46052. this.rotation.y += this.cameraRotation.y;
  46053. //rotate, if quaternion is set and rotation was used
  46054. if (this.rotationQuaternion) {
  46055. var len = this.rotation.lengthSquared();
  46056. if (len) {
  46057. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46058. }
  46059. }
  46060. if (!this.noRotationConstraint) {
  46061. var limit = (Math.PI / 2) * 0.95;
  46062. if (this.rotation.x > limit)
  46063. this.rotation.x = limit;
  46064. if (this.rotation.x < -limit)
  46065. this.rotation.x = -limit;
  46066. }
  46067. }
  46068. // Inertia
  46069. if (needToMove) {
  46070. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46071. this.cameraDirection.x = 0;
  46072. }
  46073. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46074. this.cameraDirection.y = 0;
  46075. }
  46076. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46077. this.cameraDirection.z = 0;
  46078. }
  46079. this.cameraDirection.scaleInPlace(this.inertia);
  46080. }
  46081. if (needToRotate) {
  46082. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46083. this.cameraRotation.x = 0;
  46084. }
  46085. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46086. this.cameraRotation.y = 0;
  46087. }
  46088. this.cameraRotation.scaleInPlace(this.inertia);
  46089. }
  46090. _super.prototype._checkInputs.call(this);
  46091. };
  46092. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46093. if (this.rotationQuaternion) {
  46094. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46095. }
  46096. else {
  46097. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46098. }
  46099. //update the up vector!
  46100. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46101. };
  46102. TargetCamera.prototype._getViewMatrix = function () {
  46103. if (this.lockedTarget) {
  46104. this.setTarget(this._getLockedTargetPosition());
  46105. }
  46106. // Compute
  46107. this._updateCameraRotationMatrix();
  46108. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46109. // Computing target and final matrix
  46110. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46111. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46112. return this._viewMatrix;
  46113. };
  46114. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46115. if (this.parent) {
  46116. var parentWorldMatrix = this.parent.getWorldMatrix();
  46117. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46118. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46119. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46120. this._markSyncedWithParent();
  46121. }
  46122. else {
  46123. this._globalPosition.copyFrom(this.position);
  46124. this._globalCurrentTarget.copyFrom(target);
  46125. this._globalCurrentUpVector.copyFrom(up);
  46126. }
  46127. if (this.getScene().useRightHandedSystem) {
  46128. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46129. }
  46130. else {
  46131. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46132. }
  46133. };
  46134. /**
  46135. * @override
  46136. * Override Camera.createRigCamera
  46137. */
  46138. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46139. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46140. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46141. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46142. if (!this.rotationQuaternion) {
  46143. this.rotationQuaternion = new BABYLON.Quaternion();
  46144. }
  46145. rigCamera._cameraRigParams = {};
  46146. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46147. }
  46148. return rigCamera;
  46149. }
  46150. return null;
  46151. };
  46152. /**
  46153. * @override
  46154. * Override Camera._updateRigCameras
  46155. */
  46156. TargetCamera.prototype._updateRigCameras = function () {
  46157. var camLeft = this._rigCameras[0];
  46158. var camRight = this._rigCameras[1];
  46159. switch (this.cameraRigMode) {
  46160. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46161. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46162. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46163. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46164. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46165. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46166. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46167. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46168. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46169. camLeft.setTarget(this.getTarget());
  46170. camRight.setTarget(this.getTarget());
  46171. break;
  46172. case BABYLON.Camera.RIG_MODE_VR:
  46173. if (camLeft.rotationQuaternion) {
  46174. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46175. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46176. }
  46177. else {
  46178. camLeft.rotation.copyFrom(this.rotation);
  46179. camRight.rotation.copyFrom(this.rotation);
  46180. }
  46181. camLeft.position.copyFrom(this.position);
  46182. camRight.position.copyFrom(this.position);
  46183. break;
  46184. }
  46185. _super.prototype._updateRigCameras.call(this);
  46186. };
  46187. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46188. if (!this._rigCamTransformMatrix) {
  46189. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46190. }
  46191. var target = this.getTarget();
  46192. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46193. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46194. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46195. };
  46196. TargetCamera.prototype.getClassName = function () {
  46197. return "TargetCamera";
  46198. };
  46199. __decorate([
  46200. BABYLON.serializeAsVector3()
  46201. ], TargetCamera.prototype, "rotation", void 0);
  46202. __decorate([
  46203. BABYLON.serialize()
  46204. ], TargetCamera.prototype, "speed", void 0);
  46205. __decorate([
  46206. BABYLON.serializeAsMeshReference("lockedTargetId")
  46207. ], TargetCamera.prototype, "lockedTarget", void 0);
  46208. return TargetCamera;
  46209. }(BABYLON.Camera));
  46210. BABYLON.TargetCamera = TargetCamera;
  46211. })(BABYLON || (BABYLON = {}));
  46212. //# sourceMappingURL=babylon.targetCamera.js.map
  46213. var BABYLON;
  46214. (function (BABYLON) {
  46215. var FreeCameraMouseInput = /** @class */ (function () {
  46216. function FreeCameraMouseInput(touchEnabled) {
  46217. if (touchEnabled === void 0) { touchEnabled = true; }
  46218. this.touchEnabled = touchEnabled;
  46219. this.buttons = [0, 1, 2];
  46220. this.angularSensibility = 2000.0;
  46221. this.previousPosition = null;
  46222. }
  46223. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46224. var _this = this;
  46225. var engine = this.camera.getEngine();
  46226. if (!this._pointerInput) {
  46227. this._pointerInput = function (p, s) {
  46228. var evt = p.event;
  46229. if (engine.isInVRExclusivePointerMode) {
  46230. return;
  46231. }
  46232. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46233. return;
  46234. }
  46235. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46236. return;
  46237. }
  46238. var srcElement = (evt.srcElement || evt.target);
  46239. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46240. try {
  46241. srcElement.setPointerCapture(evt.pointerId);
  46242. }
  46243. catch (e) {
  46244. //Nothing to do with the error. Execution will continue.
  46245. }
  46246. _this.previousPosition = {
  46247. x: evt.clientX,
  46248. y: evt.clientY
  46249. };
  46250. if (!noPreventDefault) {
  46251. evt.preventDefault();
  46252. element.focus();
  46253. }
  46254. }
  46255. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46256. try {
  46257. srcElement.releasePointerCapture(evt.pointerId);
  46258. }
  46259. catch (e) {
  46260. //Nothing to do with the error.
  46261. }
  46262. _this.previousPosition = null;
  46263. if (!noPreventDefault) {
  46264. evt.preventDefault();
  46265. }
  46266. }
  46267. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46268. if (!_this.previousPosition || engine.isPointerLock) {
  46269. return;
  46270. }
  46271. var offsetX = evt.clientX - _this.previousPosition.x;
  46272. if (_this.camera.getScene().useRightHandedSystem)
  46273. offsetX *= -1;
  46274. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46275. offsetX *= -1;
  46276. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46277. var offsetY = evt.clientY - _this.previousPosition.y;
  46278. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46279. _this.previousPosition = {
  46280. x: evt.clientX,
  46281. y: evt.clientY
  46282. };
  46283. if (!noPreventDefault) {
  46284. evt.preventDefault();
  46285. }
  46286. }
  46287. };
  46288. }
  46289. this._onMouseMove = function (evt) {
  46290. if (!engine.isPointerLock) {
  46291. return;
  46292. }
  46293. if (engine.isInVRExclusivePointerMode) {
  46294. return;
  46295. }
  46296. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46297. if (_this.camera.getScene().useRightHandedSystem)
  46298. offsetX *= -1;
  46299. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46300. offsetX *= -1;
  46301. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46302. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46303. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46304. _this.previousPosition = null;
  46305. if (!noPreventDefault) {
  46306. evt.preventDefault();
  46307. }
  46308. };
  46309. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46310. element.addEventListener("mousemove", this._onMouseMove, false);
  46311. };
  46312. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46313. if (this._observer && element) {
  46314. this.camera.getScene().onPointerObservable.remove(this._observer);
  46315. if (this._onMouseMove) {
  46316. element.removeEventListener("mousemove", this._onMouseMove);
  46317. }
  46318. this._observer = null;
  46319. this._onMouseMove = null;
  46320. this.previousPosition = null;
  46321. }
  46322. };
  46323. FreeCameraMouseInput.prototype.getClassName = function () {
  46324. return "FreeCameraMouseInput";
  46325. };
  46326. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46327. return "mouse";
  46328. };
  46329. __decorate([
  46330. BABYLON.serialize()
  46331. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46332. __decorate([
  46333. BABYLON.serialize()
  46334. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46335. return FreeCameraMouseInput;
  46336. }());
  46337. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46338. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46339. })(BABYLON || (BABYLON = {}));
  46340. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46341. var BABYLON;
  46342. (function (BABYLON) {
  46343. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46344. function FreeCameraKeyboardMoveInput() {
  46345. this._keys = new Array();
  46346. this.keysUp = [38];
  46347. this.keysDown = [40];
  46348. this.keysLeft = [37];
  46349. this.keysRight = [39];
  46350. }
  46351. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46352. var _this = this;
  46353. if (this._onCanvasBlurObserver) {
  46354. return;
  46355. }
  46356. this._scene = this.camera.getScene();
  46357. this._engine = this._scene.getEngine();
  46358. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46359. _this._keys = [];
  46360. });
  46361. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46362. var evt = info.event;
  46363. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46364. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46365. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46366. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46367. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46368. var index = _this._keys.indexOf(evt.keyCode);
  46369. if (index === -1) {
  46370. _this._keys.push(evt.keyCode);
  46371. }
  46372. if (!noPreventDefault) {
  46373. evt.preventDefault();
  46374. }
  46375. }
  46376. }
  46377. else {
  46378. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46379. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46380. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46381. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46382. var index = _this._keys.indexOf(evt.keyCode);
  46383. if (index >= 0) {
  46384. _this._keys.splice(index, 1);
  46385. }
  46386. if (!noPreventDefault) {
  46387. evt.preventDefault();
  46388. }
  46389. }
  46390. }
  46391. });
  46392. };
  46393. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46394. if (this._scene) {
  46395. if (this._onKeyboardObserver) {
  46396. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46397. }
  46398. if (this._onCanvasBlurObserver) {
  46399. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46400. }
  46401. this._onKeyboardObserver = null;
  46402. this._onCanvasBlurObserver = null;
  46403. }
  46404. this._keys = [];
  46405. };
  46406. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46407. if (this._onKeyboardObserver) {
  46408. var camera = this.camera;
  46409. // Keyboard
  46410. for (var index = 0; index < this._keys.length; index++) {
  46411. var keyCode = this._keys[index];
  46412. var speed = camera._computeLocalCameraSpeed();
  46413. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46414. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46415. }
  46416. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46417. camera._localDirection.copyFromFloats(0, 0, speed);
  46418. }
  46419. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46420. camera._localDirection.copyFromFloats(speed, 0, 0);
  46421. }
  46422. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46423. camera._localDirection.copyFromFloats(0, 0, -speed);
  46424. }
  46425. if (camera.getScene().useRightHandedSystem) {
  46426. camera._localDirection.z *= -1;
  46427. }
  46428. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46429. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46430. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46431. }
  46432. }
  46433. };
  46434. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46435. return "FreeCameraKeyboardMoveInput";
  46436. };
  46437. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46438. this._keys = [];
  46439. };
  46440. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46441. return "keyboard";
  46442. };
  46443. __decorate([
  46444. BABYLON.serialize()
  46445. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46446. __decorate([
  46447. BABYLON.serialize()
  46448. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46449. __decorate([
  46450. BABYLON.serialize()
  46451. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46452. __decorate([
  46453. BABYLON.serialize()
  46454. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46455. return FreeCameraKeyboardMoveInput;
  46456. }());
  46457. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46458. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46459. })(BABYLON || (BABYLON = {}));
  46460. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46461. var BABYLON;
  46462. (function (BABYLON) {
  46463. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46464. __extends(FreeCameraInputsManager, _super);
  46465. function FreeCameraInputsManager(camera) {
  46466. return _super.call(this, camera) || this;
  46467. }
  46468. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46469. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46470. return this;
  46471. };
  46472. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46473. if (touchEnabled === void 0) { touchEnabled = true; }
  46474. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46475. return this;
  46476. };
  46477. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46478. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46479. return this;
  46480. };
  46481. FreeCameraInputsManager.prototype.addTouch = function () {
  46482. this.add(new BABYLON.FreeCameraTouchInput());
  46483. return this;
  46484. };
  46485. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46486. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46487. return this;
  46488. };
  46489. return FreeCameraInputsManager;
  46490. }(BABYLON.CameraInputsManager));
  46491. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46492. })(BABYLON || (BABYLON = {}));
  46493. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46494. var BABYLON;
  46495. (function (BABYLON) {
  46496. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46497. // Forcing to use the Universal camera
  46498. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46499. });
  46500. var FreeCamera = /** @class */ (function (_super) {
  46501. __extends(FreeCamera, _super);
  46502. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46503. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46504. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46505. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46506. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46507. _this.checkCollisions = false;
  46508. _this.applyGravity = false;
  46509. _this._needMoveForGravity = false;
  46510. _this._oldPosition = BABYLON.Vector3.Zero();
  46511. _this._diffPosition = BABYLON.Vector3.Zero();
  46512. _this._newPosition = BABYLON.Vector3.Zero();
  46513. // Collisions
  46514. _this._collisionMask = -1;
  46515. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46516. if (collidedMesh === void 0) { collidedMesh = null; }
  46517. //TODO move this to the collision coordinator!
  46518. if (_this.getScene().workerCollisions)
  46519. newPosition.multiplyInPlace(_this._collider._radius);
  46520. var updatePosition = function (newPos) {
  46521. _this._newPosition.copyFrom(newPos);
  46522. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46523. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46524. _this.position.addInPlace(_this._diffPosition);
  46525. if (_this.onCollide && collidedMesh) {
  46526. _this.onCollide(collidedMesh);
  46527. }
  46528. }
  46529. };
  46530. updatePosition(newPosition);
  46531. };
  46532. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46533. _this.inputs.addKeyboard().addMouse();
  46534. return _this;
  46535. }
  46536. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46537. //-- begin properties for backward compatibility for inputs
  46538. /**
  46539. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46540. * Higher values reduce sensitivity.
  46541. */
  46542. get: function () {
  46543. var mouse = this.inputs.attached["mouse"];
  46544. if (mouse)
  46545. return mouse.angularSensibility;
  46546. return 0;
  46547. },
  46548. /**
  46549. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46550. * Higher values reduce sensitivity.
  46551. */
  46552. set: function (value) {
  46553. var mouse = this.inputs.attached["mouse"];
  46554. if (mouse)
  46555. mouse.angularSensibility = value;
  46556. },
  46557. enumerable: true,
  46558. configurable: true
  46559. });
  46560. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46561. get: function () {
  46562. var keyboard = this.inputs.attached["keyboard"];
  46563. if (keyboard)
  46564. return keyboard.keysUp;
  46565. return [];
  46566. },
  46567. set: function (value) {
  46568. var keyboard = this.inputs.attached["keyboard"];
  46569. if (keyboard)
  46570. keyboard.keysUp = value;
  46571. },
  46572. enumerable: true,
  46573. configurable: true
  46574. });
  46575. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46576. get: function () {
  46577. var keyboard = this.inputs.attached["keyboard"];
  46578. if (keyboard)
  46579. return keyboard.keysDown;
  46580. return [];
  46581. },
  46582. set: function (value) {
  46583. var keyboard = this.inputs.attached["keyboard"];
  46584. if (keyboard)
  46585. keyboard.keysDown = value;
  46586. },
  46587. enumerable: true,
  46588. configurable: true
  46589. });
  46590. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46591. get: function () {
  46592. var keyboard = this.inputs.attached["keyboard"];
  46593. if (keyboard)
  46594. return keyboard.keysLeft;
  46595. return [];
  46596. },
  46597. set: function (value) {
  46598. var keyboard = this.inputs.attached["keyboard"];
  46599. if (keyboard)
  46600. keyboard.keysLeft = value;
  46601. },
  46602. enumerable: true,
  46603. configurable: true
  46604. });
  46605. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46606. get: function () {
  46607. var keyboard = this.inputs.attached["keyboard"];
  46608. if (keyboard)
  46609. return keyboard.keysRight;
  46610. return [];
  46611. },
  46612. set: function (value) {
  46613. var keyboard = this.inputs.attached["keyboard"];
  46614. if (keyboard)
  46615. keyboard.keysRight = value;
  46616. },
  46617. enumerable: true,
  46618. configurable: true
  46619. });
  46620. // Controls
  46621. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46622. this.inputs.attachElement(element, noPreventDefault);
  46623. };
  46624. FreeCamera.prototype.detachControl = function (element) {
  46625. this.inputs.detachElement(element);
  46626. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46627. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46628. };
  46629. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46630. get: function () {
  46631. return this._collisionMask;
  46632. },
  46633. set: function (mask) {
  46634. this._collisionMask = !isNaN(mask) ? mask : -1;
  46635. },
  46636. enumerable: true,
  46637. configurable: true
  46638. });
  46639. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46640. var globalPosition;
  46641. if (this.parent) {
  46642. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46643. }
  46644. else {
  46645. globalPosition = this.position;
  46646. }
  46647. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46648. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46649. if (!this._collider) {
  46650. this._collider = new BABYLON.Collider();
  46651. }
  46652. this._collider._radius = this.ellipsoid;
  46653. this._collider.collisionMask = this._collisionMask;
  46654. //no need for clone, as long as gravity is not on.
  46655. var actualDisplacement = displacement;
  46656. //add gravity to the direction to prevent the dual-collision checking
  46657. if (this.applyGravity) {
  46658. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46659. actualDisplacement = displacement.add(this.getScene().gravity);
  46660. }
  46661. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46662. };
  46663. FreeCamera.prototype._checkInputs = function () {
  46664. if (!this._localDirection) {
  46665. this._localDirection = BABYLON.Vector3.Zero();
  46666. this._transformedDirection = BABYLON.Vector3.Zero();
  46667. }
  46668. this.inputs.checkInputs();
  46669. _super.prototype._checkInputs.call(this);
  46670. };
  46671. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46672. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46673. };
  46674. FreeCamera.prototype._updatePosition = function () {
  46675. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46676. this._collideWithWorld(this.cameraDirection);
  46677. }
  46678. else {
  46679. _super.prototype._updatePosition.call(this);
  46680. }
  46681. };
  46682. FreeCamera.prototype.dispose = function () {
  46683. this.inputs.clear();
  46684. _super.prototype.dispose.call(this);
  46685. };
  46686. FreeCamera.prototype.getClassName = function () {
  46687. return "FreeCamera";
  46688. };
  46689. __decorate([
  46690. BABYLON.serializeAsVector3()
  46691. ], FreeCamera.prototype, "ellipsoid", void 0);
  46692. __decorate([
  46693. BABYLON.serializeAsVector3()
  46694. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46695. __decorate([
  46696. BABYLON.serialize()
  46697. ], FreeCamera.prototype, "checkCollisions", void 0);
  46698. __decorate([
  46699. BABYLON.serialize()
  46700. ], FreeCamera.prototype, "applyGravity", void 0);
  46701. return FreeCamera;
  46702. }(BABYLON.TargetCamera));
  46703. BABYLON.FreeCamera = FreeCamera;
  46704. })(BABYLON || (BABYLON = {}));
  46705. //# sourceMappingURL=babylon.freeCamera.js.map
  46706. var BABYLON;
  46707. (function (BABYLON) {
  46708. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46709. function ArcRotateCameraKeyboardMoveInput() {
  46710. this._keys = new Array();
  46711. this.keysUp = [38];
  46712. this.keysDown = [40];
  46713. this.keysLeft = [37];
  46714. this.keysRight = [39];
  46715. this.keysReset = [220];
  46716. this.panningSensibility = 50.0;
  46717. this.zoomingSensibility = 25.0;
  46718. this.useAltToZoom = true;
  46719. }
  46720. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46721. var _this = this;
  46722. if (this._onCanvasBlurObserver) {
  46723. return;
  46724. }
  46725. this._scene = this.camera.getScene();
  46726. this._engine = this._scene.getEngine();
  46727. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46728. _this._keys = [];
  46729. });
  46730. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46731. var evt = info.event;
  46732. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46733. _this._ctrlPressed = evt.ctrlKey;
  46734. _this._altPressed = evt.altKey;
  46735. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46736. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46737. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46738. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46739. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46740. var index = _this._keys.indexOf(evt.keyCode);
  46741. if (index === -1) {
  46742. _this._keys.push(evt.keyCode);
  46743. }
  46744. if (evt.preventDefault) {
  46745. if (!noPreventDefault) {
  46746. evt.preventDefault();
  46747. }
  46748. }
  46749. }
  46750. }
  46751. else {
  46752. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46753. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46754. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46755. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46756. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46757. var index = _this._keys.indexOf(evt.keyCode);
  46758. if (index >= 0) {
  46759. _this._keys.splice(index, 1);
  46760. }
  46761. if (evt.preventDefault) {
  46762. if (!noPreventDefault) {
  46763. evt.preventDefault();
  46764. }
  46765. }
  46766. }
  46767. }
  46768. });
  46769. };
  46770. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46771. if (this._scene) {
  46772. if (this._onKeyboardObserver) {
  46773. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46774. }
  46775. if (this._onCanvasBlurObserver) {
  46776. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46777. }
  46778. this._onKeyboardObserver = null;
  46779. this._onCanvasBlurObserver = null;
  46780. }
  46781. this._keys = [];
  46782. };
  46783. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46784. if (this._onKeyboardObserver) {
  46785. var camera = this.camera;
  46786. for (var index = 0; index < this._keys.length; index++) {
  46787. var keyCode = this._keys[index];
  46788. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46789. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46790. camera.inertialPanningX -= 1 / this.panningSensibility;
  46791. }
  46792. else {
  46793. camera.inertialAlphaOffset -= 0.01;
  46794. }
  46795. }
  46796. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46797. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46798. camera.inertialPanningY += 1 / this.panningSensibility;
  46799. }
  46800. else if (this._altPressed && this.useAltToZoom) {
  46801. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46802. }
  46803. else {
  46804. camera.inertialBetaOffset -= 0.01;
  46805. }
  46806. }
  46807. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46808. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46809. camera.inertialPanningX += 1 / this.panningSensibility;
  46810. }
  46811. else {
  46812. camera.inertialAlphaOffset += 0.01;
  46813. }
  46814. }
  46815. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46816. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46817. camera.inertialPanningY -= 1 / this.panningSensibility;
  46818. }
  46819. else if (this._altPressed && this.useAltToZoom) {
  46820. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46821. }
  46822. else {
  46823. camera.inertialBetaOffset += 0.01;
  46824. }
  46825. }
  46826. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46827. camera.restoreState();
  46828. }
  46829. }
  46830. }
  46831. };
  46832. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46833. return "ArcRotateCameraKeyboardMoveInput";
  46834. };
  46835. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46836. return "keyboard";
  46837. };
  46838. __decorate([
  46839. BABYLON.serialize()
  46840. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46841. __decorate([
  46842. BABYLON.serialize()
  46843. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46844. __decorate([
  46845. BABYLON.serialize()
  46846. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46847. __decorate([
  46848. BABYLON.serialize()
  46849. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46850. __decorate([
  46851. BABYLON.serialize()
  46852. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46853. __decorate([
  46854. BABYLON.serialize()
  46855. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46856. __decorate([
  46857. BABYLON.serialize()
  46858. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46859. __decorate([
  46860. BABYLON.serialize()
  46861. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46862. return ArcRotateCameraKeyboardMoveInput;
  46863. }());
  46864. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46865. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46866. })(BABYLON || (BABYLON = {}));
  46867. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46868. var BABYLON;
  46869. (function (BABYLON) {
  46870. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46871. function ArcRotateCameraMouseWheelInput() {
  46872. this.wheelPrecision = 3.0;
  46873. /**
  46874. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46875. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46876. */
  46877. this.wheelDeltaPercentage = 0;
  46878. }
  46879. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46880. var _this = this;
  46881. this._wheel = function (p, s) {
  46882. //sanity check - this should be a PointerWheel event.
  46883. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46884. return;
  46885. var event = p.event;
  46886. var delta = 0;
  46887. if (event.wheelDelta) {
  46888. if (_this.wheelDeltaPercentage) {
  46889. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46890. if (event.wheelDelta > 0) {
  46891. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46892. }
  46893. else {
  46894. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46895. }
  46896. }
  46897. else {
  46898. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46899. }
  46900. }
  46901. else if (event.detail) {
  46902. delta = -event.detail / _this.wheelPrecision;
  46903. }
  46904. if (delta)
  46905. _this.camera.inertialRadiusOffset += delta;
  46906. if (event.preventDefault) {
  46907. if (!noPreventDefault) {
  46908. event.preventDefault();
  46909. }
  46910. }
  46911. };
  46912. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46913. };
  46914. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46915. if (this._observer && element) {
  46916. this.camera.getScene().onPointerObservable.remove(this._observer);
  46917. this._observer = null;
  46918. this._wheel = null;
  46919. }
  46920. };
  46921. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46922. return "ArcRotateCameraMouseWheelInput";
  46923. };
  46924. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46925. return "mousewheel";
  46926. };
  46927. __decorate([
  46928. BABYLON.serialize()
  46929. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46930. __decorate([
  46931. BABYLON.serialize()
  46932. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46933. return ArcRotateCameraMouseWheelInput;
  46934. }());
  46935. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46936. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46937. })(BABYLON || (BABYLON = {}));
  46938. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46939. var BABYLON;
  46940. (function (BABYLON) {
  46941. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46942. function ArcRotateCameraPointersInput() {
  46943. this.buttons = [0, 1, 2];
  46944. this.angularSensibilityX = 1000.0;
  46945. this.angularSensibilityY = 1000.0;
  46946. this.pinchPrecision = 12.0;
  46947. /**
  46948. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46949. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46950. */
  46951. this.pinchDeltaPercentage = 0;
  46952. this.panningSensibility = 1000.0;
  46953. this.multiTouchPanning = true;
  46954. this.multiTouchPanAndZoom = true;
  46955. this._isPanClick = false;
  46956. this.pinchInwards = true;
  46957. }
  46958. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46959. var _this = this;
  46960. var engine = this.camera.getEngine();
  46961. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46962. var pointA = null;
  46963. var pointB = null;
  46964. var previousPinchSquaredDistance = 0;
  46965. var initialDistance = 0;
  46966. var twoFingerActivityCount = 0;
  46967. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46968. this._pointerInput = function (p, s) {
  46969. var evt = p.event;
  46970. var isTouch = p.event.pointerType === "touch";
  46971. if (engine.isInVRExclusivePointerMode) {
  46972. return;
  46973. }
  46974. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46975. return;
  46976. }
  46977. var srcElement = (evt.srcElement || evt.target);
  46978. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46979. try {
  46980. srcElement.setPointerCapture(evt.pointerId);
  46981. }
  46982. catch (e) {
  46983. //Nothing to do with the error. Execution will continue.
  46984. }
  46985. // Manage panning with pan button click
  46986. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46987. // manage pointers
  46988. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46989. if (pointA === null) {
  46990. pointA = cacheSoloPointer;
  46991. }
  46992. else if (pointB === null) {
  46993. pointB = cacheSoloPointer;
  46994. }
  46995. if (!noPreventDefault) {
  46996. evt.preventDefault();
  46997. element.focus();
  46998. }
  46999. }
  47000. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47001. _this.camera.restoreState();
  47002. }
  47003. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47004. try {
  47005. srcElement.releasePointerCapture(evt.pointerId);
  47006. }
  47007. catch (e) {
  47008. //Nothing to do with the error.
  47009. }
  47010. cacheSoloPointer = null;
  47011. previousPinchSquaredDistance = 0;
  47012. previousMultiTouchPanPosition.isPaning = false;
  47013. previousMultiTouchPanPosition.isPinching = false;
  47014. twoFingerActivityCount = 0;
  47015. initialDistance = 0;
  47016. if (!isTouch) {
  47017. pointB = null; // Mouse and pen are mono pointer
  47018. }
  47019. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47020. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47021. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47022. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47023. if (engine._badOS) {
  47024. pointA = pointB = null;
  47025. }
  47026. else {
  47027. //only remove the impacted pointer in case of multitouch allowing on most
  47028. //platforms switching from rotate to zoom and pan seamlessly.
  47029. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47030. pointA = pointB;
  47031. pointB = null;
  47032. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47033. }
  47034. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47035. pointB = null;
  47036. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47037. }
  47038. else {
  47039. pointA = pointB = null;
  47040. }
  47041. }
  47042. if (!noPreventDefault) {
  47043. evt.preventDefault();
  47044. }
  47045. }
  47046. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47047. if (!noPreventDefault) {
  47048. evt.preventDefault();
  47049. }
  47050. // One button down
  47051. if (pointA && pointB === null && cacheSoloPointer) {
  47052. if (_this.panningSensibility !== 0 &&
  47053. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47054. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47055. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47056. }
  47057. else {
  47058. var offsetX = evt.clientX - cacheSoloPointer.x;
  47059. var offsetY = evt.clientY - cacheSoloPointer.y;
  47060. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47061. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47062. }
  47063. cacheSoloPointer.x = evt.clientX;
  47064. cacheSoloPointer.y = evt.clientY;
  47065. }
  47066. // Two buttons down: pinch/pan
  47067. else if (pointA && pointB) {
  47068. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47069. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47070. ed.x = evt.clientX;
  47071. ed.y = evt.clientY;
  47072. var direction = _this.pinchInwards ? 1 : -1;
  47073. var distX = pointA.x - pointB.x;
  47074. var distY = pointA.y - pointB.y;
  47075. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47076. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47077. if (previousPinchSquaredDistance === 0) {
  47078. initialDistance = pinchDistance;
  47079. previousPinchSquaredDistance = pinchSquaredDistance;
  47080. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47081. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47082. return;
  47083. }
  47084. if (_this.multiTouchPanAndZoom) {
  47085. if (_this.pinchDeltaPercentage) {
  47086. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47087. }
  47088. else {
  47089. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47090. (_this.pinchPrecision *
  47091. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47092. direction);
  47093. }
  47094. if (_this.panningSensibility !== 0) {
  47095. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47096. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47097. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47098. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47099. previousMultiTouchPanPosition.x = pointersCenterX;
  47100. previousMultiTouchPanPosition.y = pointersCenterY;
  47101. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47102. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47103. }
  47104. }
  47105. else {
  47106. twoFingerActivityCount++;
  47107. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47108. if (_this.pinchDeltaPercentage) {
  47109. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47110. }
  47111. else {
  47112. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47113. (_this.pinchPrecision *
  47114. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47115. direction);
  47116. }
  47117. previousMultiTouchPanPosition.isPaning = false;
  47118. previousMultiTouchPanPosition.isPinching = true;
  47119. }
  47120. else {
  47121. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47122. if (!previousMultiTouchPanPosition.isPaning) {
  47123. previousMultiTouchPanPosition.isPaning = true;
  47124. previousMultiTouchPanPosition.isPinching = false;
  47125. previousMultiTouchPanPosition.x = ed.x;
  47126. previousMultiTouchPanPosition.y = ed.y;
  47127. return;
  47128. }
  47129. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47130. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47131. }
  47132. }
  47133. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47134. previousMultiTouchPanPosition.x = ed.x;
  47135. previousMultiTouchPanPosition.y = ed.y;
  47136. }
  47137. }
  47138. previousPinchSquaredDistance = pinchSquaredDistance;
  47139. }
  47140. }
  47141. };
  47142. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47143. this._onContextMenu = function (evt) {
  47144. evt.preventDefault();
  47145. };
  47146. if (!this.camera._useCtrlForPanning) {
  47147. element.addEventListener("contextmenu", this._onContextMenu, false);
  47148. }
  47149. this._onLostFocus = function () {
  47150. //this._keys = [];
  47151. pointA = pointB = null;
  47152. previousPinchSquaredDistance = 0;
  47153. previousMultiTouchPanPosition.isPaning = false;
  47154. previousMultiTouchPanPosition.isPinching = false;
  47155. twoFingerActivityCount = 0;
  47156. cacheSoloPointer = null;
  47157. initialDistance = 0;
  47158. };
  47159. this._onMouseMove = function (evt) {
  47160. if (!engine.isPointerLock) {
  47161. return;
  47162. }
  47163. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47164. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47165. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47166. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47167. if (!noPreventDefault) {
  47168. evt.preventDefault();
  47169. }
  47170. };
  47171. this._onGestureStart = function (e) {
  47172. if (window.MSGesture === undefined) {
  47173. return;
  47174. }
  47175. if (!_this._MSGestureHandler) {
  47176. _this._MSGestureHandler = new MSGesture();
  47177. _this._MSGestureHandler.target = element;
  47178. }
  47179. _this._MSGestureHandler.addPointer(e.pointerId);
  47180. };
  47181. this._onGesture = function (e) {
  47182. _this.camera.radius *= e.scale;
  47183. if (e.preventDefault) {
  47184. if (!noPreventDefault) {
  47185. e.stopPropagation();
  47186. e.preventDefault();
  47187. }
  47188. }
  47189. };
  47190. element.addEventListener("mousemove", this._onMouseMove, false);
  47191. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47192. element.addEventListener("MSGestureChange", this._onGesture, false);
  47193. BABYLON.Tools.RegisterTopRootEvents([
  47194. { name: "blur", handler: this._onLostFocus }
  47195. ]);
  47196. };
  47197. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47198. if (this._onLostFocus) {
  47199. BABYLON.Tools.UnregisterTopRootEvents([
  47200. { name: "blur", handler: this._onLostFocus }
  47201. ]);
  47202. }
  47203. if (element && this._observer) {
  47204. this.camera.getScene().onPointerObservable.remove(this._observer);
  47205. this._observer = null;
  47206. if (this._onContextMenu) {
  47207. element.removeEventListener("contextmenu", this._onContextMenu);
  47208. }
  47209. if (this._onMouseMove) {
  47210. element.removeEventListener("mousemove", this._onMouseMove);
  47211. }
  47212. if (this._onGestureStart) {
  47213. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47214. }
  47215. if (this._onGesture) {
  47216. element.removeEventListener("MSGestureChange", this._onGesture);
  47217. }
  47218. this._isPanClick = false;
  47219. this.pinchInwards = true;
  47220. this._onMouseMove = null;
  47221. this._onGestureStart = null;
  47222. this._onGesture = null;
  47223. this._MSGestureHandler = null;
  47224. this._onLostFocus = null;
  47225. this._onContextMenu = null;
  47226. }
  47227. };
  47228. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47229. return "ArcRotateCameraPointersInput";
  47230. };
  47231. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47232. return "pointers";
  47233. };
  47234. __decorate([
  47235. BABYLON.serialize()
  47236. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47237. __decorate([
  47238. BABYLON.serialize()
  47239. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47240. __decorate([
  47241. BABYLON.serialize()
  47242. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47243. __decorate([
  47244. BABYLON.serialize()
  47245. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47246. __decorate([
  47247. BABYLON.serialize()
  47248. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47249. __decorate([
  47250. BABYLON.serialize()
  47251. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47252. __decorate([
  47253. BABYLON.serialize()
  47254. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47255. __decorate([
  47256. BABYLON.serialize()
  47257. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47258. return ArcRotateCameraPointersInput;
  47259. }());
  47260. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47261. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47262. })(BABYLON || (BABYLON = {}));
  47263. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47264. var BABYLON;
  47265. (function (BABYLON) {
  47266. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47267. __extends(ArcRotateCameraInputsManager, _super);
  47268. function ArcRotateCameraInputsManager(camera) {
  47269. return _super.call(this, camera) || this;
  47270. }
  47271. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47272. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47273. return this;
  47274. };
  47275. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47276. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47277. return this;
  47278. };
  47279. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47280. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47281. return this;
  47282. };
  47283. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47284. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47285. return this;
  47286. };
  47287. return ArcRotateCameraInputsManager;
  47288. }(BABYLON.CameraInputsManager));
  47289. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47290. })(BABYLON || (BABYLON = {}));
  47291. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47292. var BABYLON;
  47293. (function (BABYLON) {
  47294. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47295. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47296. });
  47297. var ArcRotateCamera = /** @class */ (function (_super) {
  47298. __extends(ArcRotateCamera, _super);
  47299. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47300. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47301. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47302. _this.inertialAlphaOffset = 0;
  47303. _this.inertialBetaOffset = 0;
  47304. _this.inertialRadiusOffset = 0;
  47305. _this.lowerAlphaLimit = null;
  47306. _this.upperAlphaLimit = null;
  47307. _this.lowerBetaLimit = 0.01;
  47308. _this.upperBetaLimit = Math.PI;
  47309. _this.lowerRadiusLimit = null;
  47310. _this.upperRadiusLimit = null;
  47311. _this.inertialPanningX = 0;
  47312. _this.inertialPanningY = 0;
  47313. _this.pinchToPanMaxDistance = 20;
  47314. _this.panningDistanceLimit = null;
  47315. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47316. _this.panningInertia = 0.9;
  47317. //-- end properties for backward compatibility for inputs
  47318. _this.zoomOnFactor = 1;
  47319. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47320. _this.allowUpsideDown = true;
  47321. _this._viewMatrix = new BABYLON.Matrix();
  47322. // Panning
  47323. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47324. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47325. _this.checkCollisions = false;
  47326. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47327. _this._previousPosition = BABYLON.Vector3.Zero();
  47328. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47329. _this._newPosition = BABYLON.Vector3.Zero();
  47330. _this._computationVector = BABYLON.Vector3.Zero();
  47331. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47332. if (collidedMesh === void 0) { collidedMesh = null; }
  47333. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47334. newPosition.multiplyInPlace(_this._collider._radius);
  47335. }
  47336. if (!collidedMesh) {
  47337. _this._previousPosition.copyFrom(_this.position);
  47338. }
  47339. else {
  47340. _this.setPosition(newPosition);
  47341. if (_this.onCollide) {
  47342. _this.onCollide(collidedMesh);
  47343. }
  47344. }
  47345. // Recompute because of constraints
  47346. var cosa = Math.cos(_this.alpha);
  47347. var sina = Math.sin(_this.alpha);
  47348. var cosb = Math.cos(_this.beta);
  47349. var sinb = Math.sin(_this.beta);
  47350. if (sinb === 0) {
  47351. sinb = 0.0001;
  47352. }
  47353. var target = _this._getTargetPosition();
  47354. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47355. target.addToRef(_this._computationVector, _this._newPosition);
  47356. _this.position.copyFrom(_this._newPosition);
  47357. var up = _this.upVector;
  47358. if (_this.allowUpsideDown && _this.beta < 0) {
  47359. up = up.clone();
  47360. up = up.negate();
  47361. }
  47362. _this._computeViewMatrix(_this.position, target, up);
  47363. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47364. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47365. _this._collisionTriggered = false;
  47366. };
  47367. _this._target = BABYLON.Vector3.Zero();
  47368. if (target) {
  47369. _this.setTarget(target);
  47370. }
  47371. _this.alpha = alpha;
  47372. _this.beta = beta;
  47373. _this.radius = radius;
  47374. _this.getViewMatrix();
  47375. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47376. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47377. return _this;
  47378. }
  47379. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47380. get: function () {
  47381. return this._target;
  47382. },
  47383. set: function (value) {
  47384. this.setTarget(value);
  47385. },
  47386. enumerable: true,
  47387. configurable: true
  47388. });
  47389. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47390. //-- begin properties for backward compatibility for inputs
  47391. get: function () {
  47392. var pointers = this.inputs.attached["pointers"];
  47393. if (pointers)
  47394. return pointers.angularSensibilityX;
  47395. return 0;
  47396. },
  47397. set: function (value) {
  47398. var pointers = this.inputs.attached["pointers"];
  47399. if (pointers) {
  47400. pointers.angularSensibilityX = value;
  47401. }
  47402. },
  47403. enumerable: true,
  47404. configurable: true
  47405. });
  47406. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47407. get: function () {
  47408. var pointers = this.inputs.attached["pointers"];
  47409. if (pointers)
  47410. return pointers.angularSensibilityY;
  47411. return 0;
  47412. },
  47413. set: function (value) {
  47414. var pointers = this.inputs.attached["pointers"];
  47415. if (pointers) {
  47416. pointers.angularSensibilityY = value;
  47417. }
  47418. },
  47419. enumerable: true,
  47420. configurable: true
  47421. });
  47422. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47423. get: function () {
  47424. var pointers = this.inputs.attached["pointers"];
  47425. if (pointers)
  47426. return pointers.pinchPrecision;
  47427. return 0;
  47428. },
  47429. set: function (value) {
  47430. var pointers = this.inputs.attached["pointers"];
  47431. if (pointers) {
  47432. pointers.pinchPrecision = value;
  47433. }
  47434. },
  47435. enumerable: true,
  47436. configurable: true
  47437. });
  47438. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47439. get: function () {
  47440. var pointers = this.inputs.attached["pointers"];
  47441. if (pointers)
  47442. return pointers.pinchDeltaPercentage;
  47443. return 0;
  47444. },
  47445. set: function (value) {
  47446. var pointers = this.inputs.attached["pointers"];
  47447. if (pointers) {
  47448. pointers.pinchDeltaPercentage = value;
  47449. }
  47450. },
  47451. enumerable: true,
  47452. configurable: true
  47453. });
  47454. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47455. get: function () {
  47456. var pointers = this.inputs.attached["pointers"];
  47457. if (pointers)
  47458. return pointers.panningSensibility;
  47459. return 0;
  47460. },
  47461. set: function (value) {
  47462. var pointers = this.inputs.attached["pointers"];
  47463. if (pointers) {
  47464. pointers.panningSensibility = value;
  47465. }
  47466. },
  47467. enumerable: true,
  47468. configurable: true
  47469. });
  47470. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47471. get: function () {
  47472. var keyboard = this.inputs.attached["keyboard"];
  47473. if (keyboard)
  47474. return keyboard.keysUp;
  47475. return [];
  47476. },
  47477. set: function (value) {
  47478. var keyboard = this.inputs.attached["keyboard"];
  47479. if (keyboard)
  47480. keyboard.keysUp = value;
  47481. },
  47482. enumerable: true,
  47483. configurable: true
  47484. });
  47485. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47486. get: function () {
  47487. var keyboard = this.inputs.attached["keyboard"];
  47488. if (keyboard)
  47489. return keyboard.keysDown;
  47490. return [];
  47491. },
  47492. set: function (value) {
  47493. var keyboard = this.inputs.attached["keyboard"];
  47494. if (keyboard)
  47495. keyboard.keysDown = value;
  47496. },
  47497. enumerable: true,
  47498. configurable: true
  47499. });
  47500. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47501. get: function () {
  47502. var keyboard = this.inputs.attached["keyboard"];
  47503. if (keyboard)
  47504. return keyboard.keysLeft;
  47505. return [];
  47506. },
  47507. set: function (value) {
  47508. var keyboard = this.inputs.attached["keyboard"];
  47509. if (keyboard)
  47510. keyboard.keysLeft = value;
  47511. },
  47512. enumerable: true,
  47513. configurable: true
  47514. });
  47515. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47516. get: function () {
  47517. var keyboard = this.inputs.attached["keyboard"];
  47518. if (keyboard)
  47519. return keyboard.keysRight;
  47520. return [];
  47521. },
  47522. set: function (value) {
  47523. var keyboard = this.inputs.attached["keyboard"];
  47524. if (keyboard)
  47525. keyboard.keysRight = value;
  47526. },
  47527. enumerable: true,
  47528. configurable: true
  47529. });
  47530. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47531. get: function () {
  47532. var mousewheel = this.inputs.attached["mousewheel"];
  47533. if (mousewheel)
  47534. return mousewheel.wheelPrecision;
  47535. return 0;
  47536. },
  47537. set: function (value) {
  47538. var mousewheel = this.inputs.attached["mousewheel"];
  47539. if (mousewheel)
  47540. mousewheel.wheelPrecision = value;
  47541. },
  47542. enumerable: true,
  47543. configurable: true
  47544. });
  47545. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47546. get: function () {
  47547. var mousewheel = this.inputs.attached["mousewheel"];
  47548. if (mousewheel)
  47549. return mousewheel.wheelDeltaPercentage;
  47550. return 0;
  47551. },
  47552. set: function (value) {
  47553. var mousewheel = this.inputs.attached["mousewheel"];
  47554. if (mousewheel)
  47555. mousewheel.wheelDeltaPercentage = value;
  47556. },
  47557. enumerable: true,
  47558. configurable: true
  47559. });
  47560. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47561. get: function () {
  47562. return this._bouncingBehavior;
  47563. },
  47564. enumerable: true,
  47565. configurable: true
  47566. });
  47567. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47568. get: function () {
  47569. return this._bouncingBehavior != null;
  47570. },
  47571. set: function (value) {
  47572. if (value === this.useBouncingBehavior) {
  47573. return;
  47574. }
  47575. if (value) {
  47576. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47577. this.addBehavior(this._bouncingBehavior);
  47578. }
  47579. else if (this._bouncingBehavior) {
  47580. this.removeBehavior(this._bouncingBehavior);
  47581. this._bouncingBehavior = null;
  47582. }
  47583. },
  47584. enumerable: true,
  47585. configurable: true
  47586. });
  47587. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47588. get: function () {
  47589. return this._framingBehavior;
  47590. },
  47591. enumerable: true,
  47592. configurable: true
  47593. });
  47594. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47595. get: function () {
  47596. return this._framingBehavior != null;
  47597. },
  47598. set: function (value) {
  47599. if (value === this.useFramingBehavior) {
  47600. return;
  47601. }
  47602. if (value) {
  47603. this._framingBehavior = new BABYLON.FramingBehavior();
  47604. this.addBehavior(this._framingBehavior);
  47605. }
  47606. else if (this._framingBehavior) {
  47607. this.removeBehavior(this._framingBehavior);
  47608. this._framingBehavior = null;
  47609. }
  47610. },
  47611. enumerable: true,
  47612. configurable: true
  47613. });
  47614. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47615. get: function () {
  47616. return this._autoRotationBehavior;
  47617. },
  47618. enumerable: true,
  47619. configurable: true
  47620. });
  47621. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47622. get: function () {
  47623. return this._autoRotationBehavior != null;
  47624. },
  47625. set: function (value) {
  47626. if (value === this.useAutoRotationBehavior) {
  47627. return;
  47628. }
  47629. if (value) {
  47630. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47631. this.addBehavior(this._autoRotationBehavior);
  47632. }
  47633. else if (this._autoRotationBehavior) {
  47634. this.removeBehavior(this._autoRotationBehavior);
  47635. this._autoRotationBehavior = null;
  47636. }
  47637. },
  47638. enumerable: true,
  47639. configurable: true
  47640. });
  47641. // Cache
  47642. ArcRotateCamera.prototype._initCache = function () {
  47643. _super.prototype._initCache.call(this);
  47644. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47645. this._cache.alpha = undefined;
  47646. this._cache.beta = undefined;
  47647. this._cache.radius = undefined;
  47648. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47649. };
  47650. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47651. if (!ignoreParentClass) {
  47652. _super.prototype._updateCache.call(this);
  47653. }
  47654. this._cache._target.copyFrom(this._getTargetPosition());
  47655. this._cache.alpha = this.alpha;
  47656. this._cache.beta = this.beta;
  47657. this._cache.radius = this.radius;
  47658. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47659. };
  47660. ArcRotateCamera.prototype._getTargetPosition = function () {
  47661. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47662. var pos = this._targetHost.getAbsolutePosition();
  47663. if (this._targetBoundingCenter) {
  47664. pos.addToRef(this._targetBoundingCenter, this._target);
  47665. }
  47666. else {
  47667. this._target.copyFrom(pos);
  47668. }
  47669. }
  47670. var lockedTargetPosition = this._getLockedTargetPosition();
  47671. if (lockedTargetPosition) {
  47672. return lockedTargetPosition;
  47673. }
  47674. return this._target;
  47675. };
  47676. ArcRotateCamera.prototype.storeState = function () {
  47677. this._storedAlpha = this.alpha;
  47678. this._storedBeta = this.beta;
  47679. this._storedRadius = this.radius;
  47680. this._storedTarget = this._getTargetPosition().clone();
  47681. return _super.prototype.storeState.call(this);
  47682. };
  47683. /**
  47684. * Restored camera state. You must call storeState() first
  47685. */
  47686. ArcRotateCamera.prototype._restoreStateValues = function () {
  47687. if (!_super.prototype._restoreStateValues.call(this)) {
  47688. return false;
  47689. }
  47690. this.alpha = this._storedAlpha;
  47691. this.beta = this._storedBeta;
  47692. this.radius = this._storedRadius;
  47693. this.setTarget(this._storedTarget.clone());
  47694. this.inertialAlphaOffset = 0;
  47695. this.inertialBetaOffset = 0;
  47696. this.inertialRadiusOffset = 0;
  47697. this.inertialPanningX = 0;
  47698. this.inertialPanningY = 0;
  47699. return true;
  47700. };
  47701. // Synchronized
  47702. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47703. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47704. return false;
  47705. return this._cache._target.equals(this._getTargetPosition())
  47706. && this._cache.alpha === this.alpha
  47707. && this._cache.beta === this.beta
  47708. && this._cache.radius === this.radius
  47709. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47710. };
  47711. // Methods
  47712. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47713. var _this = this;
  47714. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47715. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47716. this._useCtrlForPanning = useCtrlForPanning;
  47717. this._panningMouseButton = panningMouseButton;
  47718. this.inputs.attachElement(element, noPreventDefault);
  47719. this._reset = function () {
  47720. _this.inertialAlphaOffset = 0;
  47721. _this.inertialBetaOffset = 0;
  47722. _this.inertialRadiusOffset = 0;
  47723. _this.inertialPanningX = 0;
  47724. _this.inertialPanningY = 0;
  47725. };
  47726. };
  47727. ArcRotateCamera.prototype.detachControl = function (element) {
  47728. this.inputs.detachElement(element);
  47729. if (this._reset) {
  47730. this._reset();
  47731. }
  47732. };
  47733. ArcRotateCamera.prototype._checkInputs = function () {
  47734. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47735. if (this._collisionTriggered) {
  47736. return;
  47737. }
  47738. this.inputs.checkInputs();
  47739. // Inertia
  47740. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47741. var inertialAlphaOffset = this.inertialAlphaOffset;
  47742. if (this.beta <= 0)
  47743. inertialAlphaOffset *= -1;
  47744. if (this.getScene().useRightHandedSystem)
  47745. inertialAlphaOffset *= -1;
  47746. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47747. inertialAlphaOffset *= -1;
  47748. this.alpha += inertialAlphaOffset;
  47749. this.beta += this.inertialBetaOffset;
  47750. this.radius -= this.inertialRadiusOffset;
  47751. this.inertialAlphaOffset *= this.inertia;
  47752. this.inertialBetaOffset *= this.inertia;
  47753. this.inertialRadiusOffset *= this.inertia;
  47754. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47755. this.inertialAlphaOffset = 0;
  47756. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47757. this.inertialBetaOffset = 0;
  47758. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47759. this.inertialRadiusOffset = 0;
  47760. }
  47761. // Panning inertia
  47762. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47763. if (!this._localDirection) {
  47764. this._localDirection = BABYLON.Vector3.Zero();
  47765. this._transformedDirection = BABYLON.Vector3.Zero();
  47766. }
  47767. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47768. this._localDirection.multiplyInPlace(this.panningAxis);
  47769. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47770. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47771. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47772. if (!this.panningAxis.y) {
  47773. this._transformedDirection.y = 0;
  47774. }
  47775. if (!this._targetHost) {
  47776. if (this.panningDistanceLimit) {
  47777. this._transformedDirection.addInPlace(this._target);
  47778. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47779. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47780. this._target.copyFrom(this._transformedDirection);
  47781. }
  47782. }
  47783. else {
  47784. this._target.addInPlace(this._transformedDirection);
  47785. }
  47786. }
  47787. this.inertialPanningX *= this.panningInertia;
  47788. this.inertialPanningY *= this.panningInertia;
  47789. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47790. this.inertialPanningX = 0;
  47791. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47792. this.inertialPanningY = 0;
  47793. }
  47794. // Limits
  47795. this._checkLimits();
  47796. _super.prototype._checkInputs.call(this);
  47797. };
  47798. ArcRotateCamera.prototype._checkLimits = function () {
  47799. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47800. if (this.allowUpsideDown && this.beta > Math.PI) {
  47801. this.beta = this.beta - (2 * Math.PI);
  47802. }
  47803. }
  47804. else {
  47805. if (this.beta < this.lowerBetaLimit) {
  47806. this.beta = this.lowerBetaLimit;
  47807. }
  47808. }
  47809. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47810. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47811. this.beta = this.beta + (2 * Math.PI);
  47812. }
  47813. }
  47814. else {
  47815. if (this.beta > this.upperBetaLimit) {
  47816. this.beta = this.upperBetaLimit;
  47817. }
  47818. }
  47819. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47820. this.alpha = this.lowerAlphaLimit;
  47821. }
  47822. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47823. this.alpha = this.upperAlphaLimit;
  47824. }
  47825. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47826. this.radius = this.lowerRadiusLimit;
  47827. }
  47828. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47829. this.radius = this.upperRadiusLimit;
  47830. }
  47831. };
  47832. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47833. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47834. this.radius = this._computationVector.length();
  47835. if (this.radius === 0) {
  47836. this.radius = 0.0001; // Just to avoid division by zero
  47837. }
  47838. // Alpha
  47839. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47840. if (this._computationVector.z < 0) {
  47841. this.alpha = 2 * Math.PI - this.alpha;
  47842. }
  47843. // Beta
  47844. this.beta = Math.acos(this._computationVector.y / this.radius);
  47845. this._checkLimits();
  47846. };
  47847. ArcRotateCamera.prototype.setPosition = function (position) {
  47848. if (this.position.equals(position)) {
  47849. return;
  47850. }
  47851. this.position.copyFrom(position);
  47852. this.rebuildAnglesAndRadius();
  47853. };
  47854. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47855. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47856. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47857. if (target.getBoundingInfo) {
  47858. if (toBoundingCenter) {
  47859. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47860. }
  47861. else {
  47862. this._targetBoundingCenter = null;
  47863. }
  47864. this._targetHost = target;
  47865. this._target = this._getTargetPosition();
  47866. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47867. }
  47868. else {
  47869. var newTarget = target;
  47870. var currentTarget = this._getTargetPosition();
  47871. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47872. return;
  47873. }
  47874. this._targetHost = null;
  47875. this._target = newTarget;
  47876. this._targetBoundingCenter = null;
  47877. this.onMeshTargetChangedObservable.notifyObservers(null);
  47878. }
  47879. this.rebuildAnglesAndRadius();
  47880. };
  47881. ArcRotateCamera.prototype._getViewMatrix = function () {
  47882. // Compute
  47883. var cosa = Math.cos(this.alpha);
  47884. var sina = Math.sin(this.alpha);
  47885. var cosb = Math.cos(this.beta);
  47886. var sinb = Math.sin(this.beta);
  47887. if (sinb === 0) {
  47888. sinb = 0.0001;
  47889. }
  47890. var target = this._getTargetPosition();
  47891. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47892. target.addToRef(this._computationVector, this._newPosition);
  47893. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47894. if (!this._collider) {
  47895. this._collider = new BABYLON.Collider();
  47896. }
  47897. this._collider._radius = this.collisionRadius;
  47898. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47899. this._collisionTriggered = true;
  47900. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47901. }
  47902. else {
  47903. this.position.copyFrom(this._newPosition);
  47904. var up = this.upVector;
  47905. if (this.allowUpsideDown && sinb < 0) {
  47906. up = up.clone();
  47907. up = up.negate();
  47908. }
  47909. this._computeViewMatrix(this.position, target, up);
  47910. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47911. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47912. }
  47913. this._currentTarget = target;
  47914. return this._viewMatrix;
  47915. };
  47916. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47917. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47918. meshes = meshes || this.getScene().meshes;
  47919. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47920. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47921. this.radius = distance * this.zoomOnFactor;
  47922. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47923. };
  47924. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47925. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47926. var meshesOrMinMaxVector;
  47927. var distance;
  47928. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47929. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47930. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47931. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47932. }
  47933. else { //minMaxVector and distance
  47934. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47935. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47936. distance = minMaxVectorAndDistance.distance;
  47937. }
  47938. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47939. if (!doNotUpdateMaxZ) {
  47940. this.maxZ = distance * 2;
  47941. }
  47942. };
  47943. /**
  47944. * @override
  47945. * Override Camera.createRigCamera
  47946. */
  47947. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47948. var alphaShift = 0;
  47949. switch (this.cameraRigMode) {
  47950. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47951. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47952. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47953. case BABYLON.Camera.RIG_MODE_VR:
  47954. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47955. break;
  47956. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47957. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47958. break;
  47959. }
  47960. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47961. rigCam._cameraRigParams = {};
  47962. return rigCam;
  47963. };
  47964. /**
  47965. * @override
  47966. * Override Camera._updateRigCameras
  47967. */
  47968. ArcRotateCamera.prototype._updateRigCameras = function () {
  47969. var camLeft = this._rigCameras[0];
  47970. var camRight = this._rigCameras[1];
  47971. camLeft.beta = camRight.beta = this.beta;
  47972. camLeft.radius = camRight.radius = this.radius;
  47973. switch (this.cameraRigMode) {
  47974. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47975. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47976. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47977. case BABYLON.Camera.RIG_MODE_VR:
  47978. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47979. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47980. break;
  47981. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47982. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47983. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47984. break;
  47985. }
  47986. _super.prototype._updateRigCameras.call(this);
  47987. };
  47988. ArcRotateCamera.prototype.dispose = function () {
  47989. this.inputs.clear();
  47990. _super.prototype.dispose.call(this);
  47991. };
  47992. ArcRotateCamera.prototype.getClassName = function () {
  47993. return "ArcRotateCamera";
  47994. };
  47995. __decorate([
  47996. BABYLON.serialize()
  47997. ], ArcRotateCamera.prototype, "alpha", void 0);
  47998. __decorate([
  47999. BABYLON.serialize()
  48000. ], ArcRotateCamera.prototype, "beta", void 0);
  48001. __decorate([
  48002. BABYLON.serialize()
  48003. ], ArcRotateCamera.prototype, "radius", void 0);
  48004. __decorate([
  48005. BABYLON.serializeAsVector3("target")
  48006. ], ArcRotateCamera.prototype, "_target", void 0);
  48007. __decorate([
  48008. BABYLON.serialize()
  48009. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48010. __decorate([
  48011. BABYLON.serialize()
  48012. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48013. __decorate([
  48014. BABYLON.serialize()
  48015. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48016. __decorate([
  48017. BABYLON.serialize()
  48018. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48019. __decorate([
  48020. BABYLON.serialize()
  48021. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48022. __decorate([
  48023. BABYLON.serialize()
  48024. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48025. __decorate([
  48026. BABYLON.serialize()
  48027. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48028. __decorate([
  48029. BABYLON.serialize()
  48030. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48031. __decorate([
  48032. BABYLON.serialize()
  48033. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48034. __decorate([
  48035. BABYLON.serialize()
  48036. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48037. __decorate([
  48038. BABYLON.serialize()
  48039. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48040. __decorate([
  48041. BABYLON.serialize()
  48042. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48043. __decorate([
  48044. BABYLON.serialize()
  48045. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48046. __decorate([
  48047. BABYLON.serializeAsVector3()
  48048. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48049. __decorate([
  48050. BABYLON.serialize()
  48051. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48052. __decorate([
  48053. BABYLON.serialize()
  48054. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48055. __decorate([
  48056. BABYLON.serialize()
  48057. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48058. return ArcRotateCamera;
  48059. }(BABYLON.TargetCamera));
  48060. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48061. })(BABYLON || (BABYLON = {}));
  48062. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48063. var BABYLON;
  48064. (function (BABYLON) {
  48065. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48066. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48067. });
  48068. /**
  48069. * The HemisphericLight simulates the ambient environment light,
  48070. * so the passed direction is the light reflection direction, not the incoming direction.
  48071. */
  48072. var HemisphericLight = /** @class */ (function (_super) {
  48073. __extends(HemisphericLight, _super);
  48074. /**
  48075. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48076. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48077. * The HemisphericLight can't cast shadows.
  48078. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48079. * @param name The friendly name of the light
  48080. * @param direction The direction of the light reflection
  48081. * @param scene The scene the light belongs to
  48082. */
  48083. function HemisphericLight(name, direction, scene) {
  48084. var _this = _super.call(this, name, scene) || this;
  48085. /**
  48086. * The groundColor is the light in the opposite direction to the one specified during creation.
  48087. * 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.
  48088. */
  48089. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48090. _this.direction = direction || BABYLON.Vector3.Up();
  48091. return _this;
  48092. }
  48093. HemisphericLight.prototype._buildUniformLayout = function () {
  48094. this._uniformBuffer.addUniform("vLightData", 4);
  48095. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48096. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48097. this._uniformBuffer.addUniform("vLightGround", 3);
  48098. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48099. this._uniformBuffer.addUniform("depthValues", 2);
  48100. this._uniformBuffer.create();
  48101. };
  48102. /**
  48103. * Returns the string "HemisphericLight".
  48104. * @return The class name
  48105. */
  48106. HemisphericLight.prototype.getClassName = function () {
  48107. return "HemisphericLight";
  48108. };
  48109. /**
  48110. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48111. * Returns the updated direction.
  48112. * @param target The target the direction should point to
  48113. * @return The computed direction
  48114. */
  48115. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48116. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48117. return this.direction;
  48118. };
  48119. /**
  48120. * Returns the shadow generator associated to the light.
  48121. * @returns Always null for hemispheric lights because it does not support shadows.
  48122. */
  48123. HemisphericLight.prototype.getShadowGenerator = function () {
  48124. return null;
  48125. };
  48126. /**
  48127. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48128. * @param effect The effect to update
  48129. * @param lightIndex The index of the light in the effect to update
  48130. * @returns The hemispheric light
  48131. */
  48132. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48133. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48134. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48135. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48136. return this;
  48137. };
  48138. /**
  48139. * @hidden internal use only.
  48140. */
  48141. HemisphericLight.prototype._getWorldMatrix = function () {
  48142. if (!this._worldMatrix) {
  48143. this._worldMatrix = BABYLON.Matrix.Identity();
  48144. }
  48145. return this._worldMatrix;
  48146. };
  48147. /**
  48148. * Returns the integer 3.
  48149. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48150. */
  48151. HemisphericLight.prototype.getTypeID = function () {
  48152. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48153. };
  48154. /**
  48155. * Prepares the list of defines specific to the light type.
  48156. * @param defines the list of defines
  48157. * @param lightIndex defines the index of the light for the effect
  48158. */
  48159. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48160. defines["HEMILIGHT" + lightIndex] = true;
  48161. };
  48162. __decorate([
  48163. BABYLON.serializeAsColor3()
  48164. ], HemisphericLight.prototype, "groundColor", void 0);
  48165. __decorate([
  48166. BABYLON.serializeAsVector3()
  48167. ], HemisphericLight.prototype, "direction", void 0);
  48168. return HemisphericLight;
  48169. }(BABYLON.Light));
  48170. BABYLON.HemisphericLight = HemisphericLight;
  48171. })(BABYLON || (BABYLON = {}));
  48172. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48173. var BABYLON;
  48174. (function (BABYLON) {
  48175. /**
  48176. * Base implementation IShadowLight
  48177. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48178. */
  48179. var ShadowLight = /** @class */ (function (_super) {
  48180. __extends(ShadowLight, _super);
  48181. function ShadowLight() {
  48182. var _this = _super !== null && _super.apply(this, arguments) || this;
  48183. _this._needProjectionMatrixCompute = true;
  48184. return _this;
  48185. }
  48186. ShadowLight.prototype._setPosition = function (value) {
  48187. this._position = value;
  48188. };
  48189. Object.defineProperty(ShadowLight.prototype, "position", {
  48190. /**
  48191. * Sets the position the shadow will be casted from. Also use as the light position for both
  48192. * point and spot lights.
  48193. */
  48194. get: function () {
  48195. return this._position;
  48196. },
  48197. /**
  48198. * Sets the position the shadow will be casted from. Also use as the light position for both
  48199. * point and spot lights.
  48200. */
  48201. set: function (value) {
  48202. this._setPosition(value);
  48203. },
  48204. enumerable: true,
  48205. configurable: true
  48206. });
  48207. ShadowLight.prototype._setDirection = function (value) {
  48208. this._direction = value;
  48209. };
  48210. Object.defineProperty(ShadowLight.prototype, "direction", {
  48211. /**
  48212. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48213. * Also use as the light direction on spot and directional lights.
  48214. */
  48215. get: function () {
  48216. return this._direction;
  48217. },
  48218. /**
  48219. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48220. * Also use as the light direction on spot and directional lights.
  48221. */
  48222. set: function (value) {
  48223. this._setDirection(value);
  48224. },
  48225. enumerable: true,
  48226. configurable: true
  48227. });
  48228. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48229. /**
  48230. * Gets the shadow projection clipping minimum z value.
  48231. */
  48232. get: function () {
  48233. return this._shadowMinZ;
  48234. },
  48235. /**
  48236. * Sets the shadow projection clipping minimum z value.
  48237. */
  48238. set: function (value) {
  48239. this._shadowMinZ = value;
  48240. this.forceProjectionMatrixCompute();
  48241. },
  48242. enumerable: true,
  48243. configurable: true
  48244. });
  48245. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48246. /**
  48247. * Sets the shadow projection clipping maximum z value.
  48248. */
  48249. get: function () {
  48250. return this._shadowMaxZ;
  48251. },
  48252. /**
  48253. * Gets the shadow projection clipping maximum z value.
  48254. */
  48255. set: function (value) {
  48256. this._shadowMaxZ = value;
  48257. this.forceProjectionMatrixCompute();
  48258. },
  48259. enumerable: true,
  48260. configurable: true
  48261. });
  48262. /**
  48263. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48264. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48265. */
  48266. ShadowLight.prototype.computeTransformedInformation = function () {
  48267. if (this.parent && this.parent.getWorldMatrix) {
  48268. if (!this.transformedPosition) {
  48269. this.transformedPosition = BABYLON.Vector3.Zero();
  48270. }
  48271. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48272. // In case the direction is present.
  48273. if (this.direction) {
  48274. if (!this.transformedDirection) {
  48275. this.transformedDirection = BABYLON.Vector3.Zero();
  48276. }
  48277. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48278. }
  48279. return true;
  48280. }
  48281. return false;
  48282. };
  48283. /**
  48284. * Return the depth scale used for the shadow map.
  48285. * @returns the depth scale.
  48286. */
  48287. ShadowLight.prototype.getDepthScale = function () {
  48288. return 50.0;
  48289. };
  48290. /**
  48291. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48292. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48293. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48294. */
  48295. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48296. return this.transformedDirection ? this.transformedDirection : this.direction;
  48297. };
  48298. /**
  48299. * Returns the ShadowLight absolute position in the World.
  48300. * @returns the position vector in world space
  48301. */
  48302. ShadowLight.prototype.getAbsolutePosition = function () {
  48303. return this.transformedPosition ? this.transformedPosition : this.position;
  48304. };
  48305. /**
  48306. * Sets the ShadowLight direction toward the passed target.
  48307. * @param target The point tot target in local space
  48308. * @returns the updated ShadowLight direction
  48309. */
  48310. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48311. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48312. return this.direction;
  48313. };
  48314. /**
  48315. * Returns the light rotation in euler definition.
  48316. * @returns the x y z rotation in local space.
  48317. */
  48318. ShadowLight.prototype.getRotation = function () {
  48319. this.direction.normalize();
  48320. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48321. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48322. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48323. };
  48324. /**
  48325. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48326. * @returns true if a cube texture needs to be use
  48327. */
  48328. ShadowLight.prototype.needCube = function () {
  48329. return false;
  48330. };
  48331. /**
  48332. * Detects if the projection matrix requires to be recomputed this frame.
  48333. * @returns true if it requires to be recomputed otherwise, false.
  48334. */
  48335. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48336. return this._needProjectionMatrixCompute;
  48337. };
  48338. /**
  48339. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48340. */
  48341. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48342. this._needProjectionMatrixCompute = true;
  48343. };
  48344. /**
  48345. * Get the world matrix of the sahdow lights.
  48346. * @hidden Internal Use Only
  48347. */
  48348. ShadowLight.prototype._getWorldMatrix = function () {
  48349. if (!this._worldMatrix) {
  48350. this._worldMatrix = BABYLON.Matrix.Identity();
  48351. }
  48352. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48353. return this._worldMatrix;
  48354. };
  48355. /**
  48356. * Gets the minZ used for shadow according to both the scene and the light.
  48357. * @param activeCamera The camera we are returning the min for
  48358. * @returns the depth min z
  48359. */
  48360. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48361. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48362. };
  48363. /**
  48364. * Gets the maxZ used for shadow according to both the scene and the light.
  48365. * @param activeCamera The camera we are returning the max for
  48366. * @returns the depth max z
  48367. */
  48368. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48369. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48370. };
  48371. /**
  48372. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48373. * @param matrix The materix to updated with the projection information
  48374. * @param viewMatrix The transform matrix of the light
  48375. * @param renderList The list of mesh to render in the map
  48376. * @returns The current light
  48377. */
  48378. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48379. if (this.customProjectionMatrixBuilder) {
  48380. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48381. }
  48382. else {
  48383. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48384. }
  48385. return this;
  48386. };
  48387. __decorate([
  48388. BABYLON.serializeAsVector3()
  48389. ], ShadowLight.prototype, "position", null);
  48390. __decorate([
  48391. BABYLON.serializeAsVector3()
  48392. ], ShadowLight.prototype, "direction", null);
  48393. __decorate([
  48394. BABYLON.serialize()
  48395. ], ShadowLight.prototype, "shadowMinZ", null);
  48396. __decorate([
  48397. BABYLON.serialize()
  48398. ], ShadowLight.prototype, "shadowMaxZ", null);
  48399. return ShadowLight;
  48400. }(BABYLON.Light));
  48401. BABYLON.ShadowLight = ShadowLight;
  48402. })(BABYLON || (BABYLON = {}));
  48403. //# sourceMappingURL=babylon.shadowLight.js.map
  48404. var BABYLON;
  48405. (function (BABYLON) {
  48406. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48407. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48408. });
  48409. /**
  48410. * A point light is a light defined by an unique point in world space.
  48411. * The light is emitted in every direction from this point.
  48412. * A good example of a point light is a standard light bulb.
  48413. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48414. */
  48415. var PointLight = /** @class */ (function (_super) {
  48416. __extends(PointLight, _super);
  48417. /**
  48418. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48419. * A PointLight emits the light in every direction.
  48420. * It can cast shadows.
  48421. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48422. * ```javascript
  48423. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48424. * ```
  48425. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48426. * @param name The light friendly name
  48427. * @param position The position of the point light in the scene
  48428. * @param scene The scene the lights belongs to
  48429. */
  48430. function PointLight(name, position, scene) {
  48431. var _this = _super.call(this, name, scene) || this;
  48432. _this._shadowAngle = Math.PI / 2;
  48433. _this.position = position;
  48434. return _this;
  48435. }
  48436. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48437. /**
  48438. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48439. * This specifies what angle the shadow will use to be created.
  48440. *
  48441. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48442. */
  48443. get: function () {
  48444. return this._shadowAngle;
  48445. },
  48446. /**
  48447. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48448. * This specifies what angle the shadow will use to be created.
  48449. *
  48450. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48451. */
  48452. set: function (value) {
  48453. this._shadowAngle = value;
  48454. this.forceProjectionMatrixCompute();
  48455. },
  48456. enumerable: true,
  48457. configurable: true
  48458. });
  48459. Object.defineProperty(PointLight.prototype, "direction", {
  48460. /**
  48461. * Gets the direction if it has been set.
  48462. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48463. */
  48464. get: function () {
  48465. return this._direction;
  48466. },
  48467. /**
  48468. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48469. */
  48470. set: function (value) {
  48471. var previousNeedCube = this.needCube();
  48472. this._direction = value;
  48473. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48474. this._shadowGenerator.recreateShadowMap();
  48475. }
  48476. },
  48477. enumerable: true,
  48478. configurable: true
  48479. });
  48480. /**
  48481. * Returns the string "PointLight"
  48482. * @returns the class name
  48483. */
  48484. PointLight.prototype.getClassName = function () {
  48485. return "PointLight";
  48486. };
  48487. /**
  48488. * Returns the integer 0.
  48489. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48490. */
  48491. PointLight.prototype.getTypeID = function () {
  48492. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48493. };
  48494. /**
  48495. * Specifies wether or not the shadowmap should be a cube texture.
  48496. * @returns true if the shadowmap needs to be a cube texture.
  48497. */
  48498. PointLight.prototype.needCube = function () {
  48499. return !this.direction;
  48500. };
  48501. /**
  48502. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48503. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48504. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48505. */
  48506. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48507. if (this.direction) {
  48508. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48509. }
  48510. else {
  48511. switch (faceIndex) {
  48512. case 0:
  48513. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48514. case 1:
  48515. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48516. case 2:
  48517. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48518. case 3:
  48519. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48520. case 4:
  48521. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48522. case 5:
  48523. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48524. }
  48525. }
  48526. return BABYLON.Vector3.Zero();
  48527. };
  48528. /**
  48529. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48530. * - fov = PI / 2
  48531. * - aspect ratio : 1.0
  48532. * - z-near and far equal to the active camera minZ and maxZ.
  48533. * Returns the PointLight.
  48534. */
  48535. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48536. var activeCamera = this.getScene().activeCamera;
  48537. if (!activeCamera) {
  48538. return;
  48539. }
  48540. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48541. };
  48542. PointLight.prototype._buildUniformLayout = function () {
  48543. this._uniformBuffer.addUniform("vLightData", 4);
  48544. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48545. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48546. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48547. this._uniformBuffer.addUniform("depthValues", 2);
  48548. this._uniformBuffer.create();
  48549. };
  48550. /**
  48551. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48552. * @param effect The effect to update
  48553. * @param lightIndex The index of the light in the effect to update
  48554. * @returns The point light
  48555. */
  48556. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48557. if (this.computeTransformedInformation()) {
  48558. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48559. return this;
  48560. }
  48561. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48562. return this;
  48563. };
  48564. /**
  48565. * Prepares the list of defines specific to the light type.
  48566. * @param defines the list of defines
  48567. * @param lightIndex defines the index of the light for the effect
  48568. */
  48569. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48570. defines["POINTLIGHT" + lightIndex] = true;
  48571. };
  48572. __decorate([
  48573. BABYLON.serialize()
  48574. ], PointLight.prototype, "shadowAngle", null);
  48575. return PointLight;
  48576. }(BABYLON.ShadowLight));
  48577. BABYLON.PointLight = PointLight;
  48578. })(BABYLON || (BABYLON = {}));
  48579. //# sourceMappingURL=babylon.pointLight.js.map
  48580. var BABYLON;
  48581. (function (BABYLON) {
  48582. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48583. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48584. });
  48585. /**
  48586. * A directional light is defined by a direction (what a surprise!).
  48587. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48588. * 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.
  48589. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48590. */
  48591. var DirectionalLight = /** @class */ (function (_super) {
  48592. __extends(DirectionalLight, _super);
  48593. /**
  48594. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48595. * The directional light is emitted from everywhere in the given direction.
  48596. * It can cast shawdows.
  48597. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48598. * @param name The friendly name of the light
  48599. * @param direction The direction of the light
  48600. * @param scene The scene the light belongs to
  48601. */
  48602. function DirectionalLight(name, direction, scene) {
  48603. var _this = _super.call(this, name, scene) || this;
  48604. _this._shadowFrustumSize = 0;
  48605. _this._shadowOrthoScale = 0.1;
  48606. /**
  48607. * Automatically compute the projection matrix to best fit (including all the casters)
  48608. * on each frame.
  48609. */
  48610. _this.autoUpdateExtends = true;
  48611. // Cache
  48612. _this._orthoLeft = Number.MAX_VALUE;
  48613. _this._orthoRight = Number.MIN_VALUE;
  48614. _this._orthoTop = Number.MIN_VALUE;
  48615. _this._orthoBottom = Number.MAX_VALUE;
  48616. _this.position = direction.scale(-1.0);
  48617. _this.direction = direction;
  48618. return _this;
  48619. }
  48620. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48621. /**
  48622. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48623. */
  48624. get: function () {
  48625. return this._shadowFrustumSize;
  48626. },
  48627. /**
  48628. * Specifies a fix frustum size for the shadow generation.
  48629. */
  48630. set: function (value) {
  48631. this._shadowFrustumSize = value;
  48632. this.forceProjectionMatrixCompute();
  48633. },
  48634. enumerable: true,
  48635. configurable: true
  48636. });
  48637. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48638. /**
  48639. * Gets the shadow projection scale against the optimal computed one.
  48640. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48641. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48642. */
  48643. get: function () {
  48644. return this._shadowOrthoScale;
  48645. },
  48646. /**
  48647. * Sets the shadow projection scale against the optimal computed one.
  48648. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48649. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48650. */
  48651. set: function (value) {
  48652. this._shadowOrthoScale = value;
  48653. this.forceProjectionMatrixCompute();
  48654. },
  48655. enumerable: true,
  48656. configurable: true
  48657. });
  48658. /**
  48659. * Returns the string "DirectionalLight".
  48660. * @return The class name
  48661. */
  48662. DirectionalLight.prototype.getClassName = function () {
  48663. return "DirectionalLight";
  48664. };
  48665. /**
  48666. * Returns the integer 1.
  48667. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48668. */
  48669. DirectionalLight.prototype.getTypeID = function () {
  48670. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48671. };
  48672. /**
  48673. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48674. * Returns the DirectionalLight Shadow projection matrix.
  48675. */
  48676. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48677. if (this.shadowFrustumSize > 0) {
  48678. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48679. }
  48680. else {
  48681. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48682. }
  48683. };
  48684. /**
  48685. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48686. * Returns the DirectionalLight Shadow projection matrix.
  48687. */
  48688. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48689. var activeCamera = this.getScene().activeCamera;
  48690. if (!activeCamera) {
  48691. return;
  48692. }
  48693. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48694. };
  48695. /**
  48696. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48697. * Returns the DirectionalLight Shadow projection matrix.
  48698. */
  48699. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48700. var activeCamera = this.getScene().activeCamera;
  48701. if (!activeCamera) {
  48702. return;
  48703. }
  48704. // Check extends
  48705. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48706. var tempVector3 = BABYLON.Vector3.Zero();
  48707. this._orthoLeft = Number.MAX_VALUE;
  48708. this._orthoRight = Number.MIN_VALUE;
  48709. this._orthoTop = Number.MIN_VALUE;
  48710. this._orthoBottom = Number.MAX_VALUE;
  48711. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48712. var mesh = renderList[meshIndex];
  48713. if (!mesh) {
  48714. continue;
  48715. }
  48716. var boundingInfo = mesh.getBoundingInfo();
  48717. var boundingBox = boundingInfo.boundingBox;
  48718. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48719. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48720. if (tempVector3.x < this._orthoLeft)
  48721. this._orthoLeft = tempVector3.x;
  48722. if (tempVector3.y < this._orthoBottom)
  48723. this._orthoBottom = tempVector3.y;
  48724. if (tempVector3.x > this._orthoRight)
  48725. this._orthoRight = tempVector3.x;
  48726. if (tempVector3.y > this._orthoTop)
  48727. this._orthoTop = tempVector3.y;
  48728. }
  48729. }
  48730. }
  48731. var xOffset = this._orthoRight - this._orthoLeft;
  48732. var yOffset = this._orthoTop - this._orthoBottom;
  48733. 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);
  48734. };
  48735. DirectionalLight.prototype._buildUniformLayout = function () {
  48736. this._uniformBuffer.addUniform("vLightData", 4);
  48737. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48738. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48739. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48740. this._uniformBuffer.addUniform("depthValues", 2);
  48741. this._uniformBuffer.create();
  48742. };
  48743. /**
  48744. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48745. * @param effect The effect to update
  48746. * @param lightIndex The index of the light in the effect to update
  48747. * @returns The directional light
  48748. */
  48749. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48750. if (this.computeTransformedInformation()) {
  48751. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48752. return this;
  48753. }
  48754. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48755. return this;
  48756. };
  48757. /**
  48758. * Gets the minZ used for shadow according to both the scene and the light.
  48759. *
  48760. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48761. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48762. * @param activeCamera The camera we are returning the min for
  48763. * @returns the depth min z
  48764. */
  48765. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48766. return 1;
  48767. };
  48768. /**
  48769. * Gets the maxZ used for shadow according to both the scene and the light.
  48770. *
  48771. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48772. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48773. * @param activeCamera The camera we are returning the max for
  48774. * @returns the depth max z
  48775. */
  48776. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48777. return 1;
  48778. };
  48779. /**
  48780. * Prepares the list of defines specific to the light type.
  48781. * @param defines the list of defines
  48782. * @param lightIndex defines the index of the light for the effect
  48783. */
  48784. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48785. defines["DIRLIGHT" + lightIndex] = true;
  48786. };
  48787. __decorate([
  48788. BABYLON.serialize()
  48789. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48790. __decorate([
  48791. BABYLON.serialize()
  48792. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48793. __decorate([
  48794. BABYLON.serialize()
  48795. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48796. return DirectionalLight;
  48797. }(BABYLON.ShadowLight));
  48798. BABYLON.DirectionalLight = DirectionalLight;
  48799. })(BABYLON || (BABYLON = {}));
  48800. //# sourceMappingURL=babylon.directionalLight.js.map
  48801. var BABYLON;
  48802. (function (BABYLON) {
  48803. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48804. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48805. });
  48806. /**
  48807. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48808. * These values define a cone of light starting from the position, emitting toward the direction.
  48809. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48810. * and the exponent defines the speed of the decay of the light with distance (reach).
  48811. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48812. */
  48813. var SpotLight = /** @class */ (function (_super) {
  48814. __extends(SpotLight, _super);
  48815. /**
  48816. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48817. * It can cast shadows.
  48818. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48819. * @param name The light friendly name
  48820. * @param position The position of the spot light in the scene
  48821. * @param direction The direction of the light in the scene
  48822. * @param angle The cone angle of the light in Radians
  48823. * @param exponent The light decay speed with the distance from the emission spot
  48824. * @param scene The scene the lights belongs to
  48825. */
  48826. function SpotLight(name, position, direction, angle, exponent, scene) {
  48827. var _this = _super.call(this, name, scene) || this;
  48828. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48829. _this._projectionTextureLightNear = 1e-6;
  48830. _this._projectionTextureLightFar = 1000.0;
  48831. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48832. _this._projectionTextureViewLightDirty = true;
  48833. _this._projectionTextureProjectionLightDirty = true;
  48834. _this._projectionTextureDirty = true;
  48835. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48836. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48837. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48838. _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);
  48839. _this.position = position;
  48840. _this.direction = direction;
  48841. _this.angle = angle;
  48842. _this.exponent = exponent;
  48843. return _this;
  48844. }
  48845. Object.defineProperty(SpotLight.prototype, "angle", {
  48846. /**
  48847. * Gets the cone angle of the spot light in Radians.
  48848. */
  48849. get: function () {
  48850. return this._angle;
  48851. },
  48852. /**
  48853. * Sets the cone angle of the spot light in Radians.
  48854. */
  48855. set: function (value) {
  48856. this._angle = value;
  48857. this._projectionTextureProjectionLightDirty = true;
  48858. this.forceProjectionMatrixCompute();
  48859. },
  48860. enumerable: true,
  48861. configurable: true
  48862. });
  48863. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48864. /**
  48865. * Allows scaling the angle of the light for shadow generation only.
  48866. */
  48867. get: function () {
  48868. return this._shadowAngleScale;
  48869. },
  48870. /**
  48871. * Allows scaling the angle of the light for shadow generation only.
  48872. */
  48873. set: function (value) {
  48874. this._shadowAngleScale = value;
  48875. this.forceProjectionMatrixCompute();
  48876. },
  48877. enumerable: true,
  48878. configurable: true
  48879. });
  48880. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48881. /**
  48882. * Allows reading the projecton texture
  48883. */
  48884. get: function () {
  48885. return this._projectionTextureMatrix;
  48886. },
  48887. enumerable: true,
  48888. configurable: true
  48889. });
  48890. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48891. /**
  48892. * Gets the near clip of the Spotlight for texture projection.
  48893. */
  48894. get: function () {
  48895. return this._projectionTextureLightNear;
  48896. },
  48897. /**
  48898. * Sets the near clip of the Spotlight for texture projection.
  48899. */
  48900. set: function (value) {
  48901. this._projectionTextureLightNear = value;
  48902. this._projectionTextureProjectionLightDirty = true;
  48903. },
  48904. enumerable: true,
  48905. configurable: true
  48906. });
  48907. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48908. /**
  48909. * Gets the far clip of the Spotlight for texture projection.
  48910. */
  48911. get: function () {
  48912. return this._projectionTextureLightFar;
  48913. },
  48914. /**
  48915. * Sets the far clip of the Spotlight for texture projection.
  48916. */
  48917. set: function (value) {
  48918. this._projectionTextureLightFar = value;
  48919. this._projectionTextureProjectionLightDirty = true;
  48920. },
  48921. enumerable: true,
  48922. configurable: true
  48923. });
  48924. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48925. /**
  48926. * Gets the Up vector of the Spotlight for texture projection.
  48927. */
  48928. get: function () {
  48929. return this._projectionTextureUpDirection;
  48930. },
  48931. /**
  48932. * Sets the Up vector of the Spotlight for texture projection.
  48933. */
  48934. set: function (value) {
  48935. this._projectionTextureUpDirection = value;
  48936. this._projectionTextureProjectionLightDirty = true;
  48937. },
  48938. enumerable: true,
  48939. configurable: true
  48940. });
  48941. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48942. /**
  48943. * Gets the projection texture of the light.
  48944. */
  48945. get: function () {
  48946. return this._projectionTexture;
  48947. },
  48948. /**
  48949. * Sets the projection texture of the light.
  48950. */
  48951. set: function (value) {
  48952. this._projectionTexture = value;
  48953. this._projectionTextureDirty = true;
  48954. },
  48955. enumerable: true,
  48956. configurable: true
  48957. });
  48958. /**
  48959. * Returns the string "SpotLight".
  48960. * @returns the class name
  48961. */
  48962. SpotLight.prototype.getClassName = function () {
  48963. return "SpotLight";
  48964. };
  48965. /**
  48966. * Returns the integer 2.
  48967. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48968. */
  48969. SpotLight.prototype.getTypeID = function () {
  48970. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48971. };
  48972. /**
  48973. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48974. */
  48975. SpotLight.prototype._setDirection = function (value) {
  48976. _super.prototype._setDirection.call(this, value);
  48977. this._projectionTextureViewLightDirty = true;
  48978. };
  48979. /**
  48980. * Overrides the position setter to recompute the projection texture view light Matrix.
  48981. */
  48982. SpotLight.prototype._setPosition = function (value) {
  48983. _super.prototype._setPosition.call(this, value);
  48984. this._projectionTextureViewLightDirty = true;
  48985. };
  48986. /**
  48987. * 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.
  48988. * Returns the SpotLight.
  48989. */
  48990. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48991. var activeCamera = this.getScene().activeCamera;
  48992. if (!activeCamera) {
  48993. return;
  48994. }
  48995. this._shadowAngleScale = this._shadowAngleScale || 1;
  48996. var angle = this._shadowAngleScale * this._angle;
  48997. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48998. };
  48999. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49000. this._projectionTextureViewLightDirty = false;
  49001. this._projectionTextureDirty = true;
  49002. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49003. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49004. };
  49005. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49006. this._projectionTextureProjectionLightDirty = false;
  49007. this._projectionTextureDirty = true;
  49008. var light_far = this.projectionTextureLightFar;
  49009. var light_near = this.projectionTextureLightNear;
  49010. var P = light_far / (light_far - light_near);
  49011. var Q = -P * light_near;
  49012. var S = 1.0 / Math.tan(this._angle / 2.0);
  49013. var A = 1.0;
  49014. 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);
  49015. };
  49016. /**
  49017. * Main function for light texture projection matrix computing.
  49018. */
  49019. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49020. this._projectionTextureDirty = false;
  49021. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49022. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49023. };
  49024. SpotLight.prototype._buildUniformLayout = function () {
  49025. this._uniformBuffer.addUniform("vLightData", 4);
  49026. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49027. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49028. this._uniformBuffer.addUniform("vLightDirection", 3);
  49029. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49030. this._uniformBuffer.addUniform("depthValues", 2);
  49031. this._uniformBuffer.create();
  49032. };
  49033. /**
  49034. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49035. * @param effect The effect to update
  49036. * @param lightIndex The index of the light in the effect to update
  49037. * @returns The spot light
  49038. */
  49039. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49040. var normalizeDirection;
  49041. if (this.computeTransformedInformation()) {
  49042. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49043. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49044. }
  49045. else {
  49046. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49047. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49048. }
  49049. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49050. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49051. if (this._projectionTextureViewLightDirty) {
  49052. this._computeProjectionTextureViewLightMatrix();
  49053. }
  49054. if (this._projectionTextureProjectionLightDirty) {
  49055. this._computeProjectionTextureProjectionLightMatrix();
  49056. }
  49057. if (this._projectionTextureDirty) {
  49058. this._computeProjectionTextureMatrix();
  49059. }
  49060. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49061. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49062. }
  49063. return this;
  49064. };
  49065. /**
  49066. * Disposes the light and the associated resources.
  49067. */
  49068. SpotLight.prototype.dispose = function () {
  49069. _super.prototype.dispose.call(this);
  49070. if (this._projectionTexture) {
  49071. this._projectionTexture.dispose();
  49072. }
  49073. };
  49074. /**
  49075. * Prepares the list of defines specific to the light type.
  49076. * @param defines the list of defines
  49077. * @param lightIndex defines the index of the light for the effect
  49078. */
  49079. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49080. defines["SPOTLIGHT" + lightIndex] = true;
  49081. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49082. };
  49083. __decorate([
  49084. BABYLON.serialize()
  49085. ], SpotLight.prototype, "angle", null);
  49086. __decorate([
  49087. BABYLON.serialize()
  49088. ], SpotLight.prototype, "shadowAngleScale", null);
  49089. __decorate([
  49090. BABYLON.serialize()
  49091. ], SpotLight.prototype, "exponent", void 0);
  49092. __decorate([
  49093. BABYLON.serialize()
  49094. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49095. __decorate([
  49096. BABYLON.serialize()
  49097. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49098. __decorate([
  49099. BABYLON.serialize()
  49100. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49101. __decorate([
  49102. BABYLON.serializeAsTexture("projectedLightTexture")
  49103. ], SpotLight.prototype, "_projectionTexture", void 0);
  49104. return SpotLight;
  49105. }(BABYLON.ShadowLight));
  49106. BABYLON.SpotLight = SpotLight;
  49107. })(BABYLON || (BABYLON = {}));
  49108. //# sourceMappingURL=babylon.spotLight.js.map
  49109. var BABYLON;
  49110. (function (BABYLON) {
  49111. /**
  49112. * Class used to override all child animations of a given target
  49113. */
  49114. var AnimationPropertiesOverride = /** @class */ (function () {
  49115. function AnimationPropertiesOverride() {
  49116. /**
  49117. * Gets or sets a value indicating if animation blending must be used
  49118. */
  49119. this.enableBlending = false;
  49120. /**
  49121. * Gets or sets the blending speed to use when enableBlending is true
  49122. */
  49123. this.blendingSpeed = 0.01;
  49124. /**
  49125. * Gets or sets the default loop mode to use
  49126. */
  49127. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49128. }
  49129. return AnimationPropertiesOverride;
  49130. }());
  49131. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49132. })(BABYLON || (BABYLON = {}));
  49133. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49134. var BABYLON;
  49135. (function (BABYLON) {
  49136. /**
  49137. * Represents the range of an animation
  49138. */
  49139. var AnimationRange = /** @class */ (function () {
  49140. /**
  49141. * Initializes the range of an animation
  49142. * @param name The name of the animation range
  49143. * @param from The starting frame of the animation
  49144. * @param to The ending frame of the animation
  49145. */
  49146. function AnimationRange(
  49147. /**The name of the animation range**/
  49148. name,
  49149. /**The starting frame of the animation */
  49150. from,
  49151. /**The ending frame of the animation*/
  49152. to) {
  49153. this.name = name;
  49154. this.from = from;
  49155. this.to = to;
  49156. }
  49157. /**
  49158. * Makes a copy of the animation range
  49159. * @returns A copy of the animation range
  49160. */
  49161. AnimationRange.prototype.clone = function () {
  49162. return new AnimationRange(this.name, this.from, this.to);
  49163. };
  49164. return AnimationRange;
  49165. }());
  49166. BABYLON.AnimationRange = AnimationRange;
  49167. /**
  49168. * Composed of a frame, and an action function
  49169. */
  49170. var AnimationEvent = /** @class */ (function () {
  49171. /**
  49172. * Initializes the animation event
  49173. * @param frame The frame for which the event is triggered
  49174. * @param action The event to perform when triggered
  49175. * @param onlyOnce Specifies if the event should be triggered only once
  49176. */
  49177. function AnimationEvent(
  49178. /** The frame for which the event is triggered **/
  49179. frame,
  49180. /** The event to perform when triggered **/
  49181. action,
  49182. /** Specifies if the event should be triggered only once**/
  49183. onlyOnce) {
  49184. this.frame = frame;
  49185. this.action = action;
  49186. this.onlyOnce = onlyOnce;
  49187. /**
  49188. * Specifies if the animation event is done
  49189. */
  49190. this.isDone = false;
  49191. }
  49192. /** @hidden */
  49193. AnimationEvent.prototype._clone = function () {
  49194. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49195. };
  49196. return AnimationEvent;
  49197. }());
  49198. BABYLON.AnimationEvent = AnimationEvent;
  49199. /**
  49200. * A cursor which tracks a point on a path
  49201. */
  49202. var PathCursor = /** @class */ (function () {
  49203. /**
  49204. * Initializes the path cursor
  49205. * @param path The path to track
  49206. */
  49207. function PathCursor(path) {
  49208. this.path = path;
  49209. /**
  49210. * Stores path cursor callbacks for when an onchange event is triggered
  49211. */
  49212. this._onchange = new Array();
  49213. /**
  49214. * The value of the path cursor
  49215. */
  49216. this.value = 0;
  49217. /**
  49218. * The animation array of the path cursor
  49219. */
  49220. this.animations = new Array();
  49221. }
  49222. /**
  49223. * Gets the cursor point on the path
  49224. * @returns A point on the path cursor at the cursor location
  49225. */
  49226. PathCursor.prototype.getPoint = function () {
  49227. var point = this.path.getPointAtLengthPosition(this.value);
  49228. return new BABYLON.Vector3(point.x, 0, point.y);
  49229. };
  49230. /**
  49231. * Moves the cursor ahead by the step amount
  49232. * @param step The amount to move the cursor forward
  49233. * @returns This path cursor
  49234. */
  49235. PathCursor.prototype.moveAhead = function (step) {
  49236. if (step === void 0) { step = 0.002; }
  49237. this.move(step);
  49238. return this;
  49239. };
  49240. /**
  49241. * Moves the cursor behind by the step amount
  49242. * @param step The amount to move the cursor back
  49243. * @returns This path cursor
  49244. */
  49245. PathCursor.prototype.moveBack = function (step) {
  49246. if (step === void 0) { step = 0.002; }
  49247. this.move(-step);
  49248. return this;
  49249. };
  49250. /**
  49251. * Moves the cursor by the step amount
  49252. * If the step amount is greater than one, an exception is thrown
  49253. * @param step The amount to move the cursor
  49254. * @returns This path cursor
  49255. */
  49256. PathCursor.prototype.move = function (step) {
  49257. if (Math.abs(step) > 1) {
  49258. throw "step size should be less than 1.";
  49259. }
  49260. this.value += step;
  49261. this.ensureLimits();
  49262. this.raiseOnChange();
  49263. return this;
  49264. };
  49265. /**
  49266. * Ensures that the value is limited between zero and one
  49267. * @returns This path cursor
  49268. */
  49269. PathCursor.prototype.ensureLimits = function () {
  49270. while (this.value > 1) {
  49271. this.value -= 1;
  49272. }
  49273. while (this.value < 0) {
  49274. this.value += 1;
  49275. }
  49276. return this;
  49277. };
  49278. /**
  49279. * Runs onchange callbacks on change (used by the animation engine)
  49280. * @returns This path cursor
  49281. */
  49282. PathCursor.prototype.raiseOnChange = function () {
  49283. var _this = this;
  49284. this._onchange.forEach(function (f) { return f(_this); });
  49285. return this;
  49286. };
  49287. /**
  49288. * Executes a function on change
  49289. * @param f A path cursor onchange callback
  49290. * @returns This path cursor
  49291. */
  49292. PathCursor.prototype.onchange = function (f) {
  49293. this._onchange.push(f);
  49294. return this;
  49295. };
  49296. return PathCursor;
  49297. }());
  49298. BABYLON.PathCursor = PathCursor;
  49299. /**
  49300. * Enum for the animation key frame interpolation type
  49301. */
  49302. var AnimationKeyInterpolation;
  49303. (function (AnimationKeyInterpolation) {
  49304. /**
  49305. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49306. */
  49307. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49308. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49309. /**
  49310. * Class used to store any kind of animation
  49311. */
  49312. var Animation = /** @class */ (function () {
  49313. /**
  49314. * Initializes the animation
  49315. * @param name Name of the animation
  49316. * @param targetProperty Property to animate
  49317. * @param framePerSecond The frames per second of the animation
  49318. * @param dataType The data type of the animation
  49319. * @param loopMode The loop mode of the animation
  49320. * @param enableBlendings Specifies if blending should be enabled
  49321. */
  49322. function Animation(
  49323. /**Name of the animation */
  49324. name,
  49325. /**Property to animate */
  49326. targetProperty,
  49327. /**The frames per second of the animation */
  49328. framePerSecond,
  49329. /**The data type of the animation */
  49330. dataType,
  49331. /**The loop mode of the animation */
  49332. loopMode,
  49333. /**Specifies if blending should be enabled */
  49334. enableBlending) {
  49335. this.name = name;
  49336. this.targetProperty = targetProperty;
  49337. this.framePerSecond = framePerSecond;
  49338. this.dataType = dataType;
  49339. this.loopMode = loopMode;
  49340. this.enableBlending = enableBlending;
  49341. /**
  49342. * @hidden Internal use only
  49343. */
  49344. this._runtimeAnimations = new Array();
  49345. /**
  49346. * The set of event that will be linked to this animation
  49347. */
  49348. this._events = new Array();
  49349. /**
  49350. * Stores the blending speed of the animation
  49351. */
  49352. this.blendingSpeed = 0.01;
  49353. /**
  49354. * Stores the animation ranges for the animation
  49355. */
  49356. this._ranges = {};
  49357. this.targetPropertyPath = targetProperty.split(".");
  49358. this.dataType = dataType;
  49359. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49360. }
  49361. /**
  49362. * @hidden Internal use
  49363. */
  49364. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49365. var dataType = undefined;
  49366. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49367. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49368. }
  49369. else if (from instanceof BABYLON.Quaternion) {
  49370. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49371. }
  49372. else if (from instanceof BABYLON.Vector3) {
  49373. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49374. }
  49375. else if (from instanceof BABYLON.Vector2) {
  49376. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49377. }
  49378. else if (from instanceof BABYLON.Color3) {
  49379. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49380. }
  49381. else if (from instanceof BABYLON.Size) {
  49382. dataType = Animation.ANIMATIONTYPE_SIZE;
  49383. }
  49384. if (dataType == undefined) {
  49385. return null;
  49386. }
  49387. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49388. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49389. animation.setKeys(keys);
  49390. if (easingFunction !== undefined) {
  49391. animation.setEasingFunction(easingFunction);
  49392. }
  49393. return animation;
  49394. };
  49395. /**
  49396. * Sets up an animation
  49397. * @param property The property to animate
  49398. * @param animationType The animation type to apply
  49399. * @param framePerSecond The frames per second of the animation
  49400. * @param easingFunction The easing function used in the animation
  49401. * @returns The created animation
  49402. */
  49403. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49404. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49405. animation.setEasingFunction(easingFunction);
  49406. return animation;
  49407. };
  49408. /**
  49409. * Create and start an animation on a node
  49410. * @param name defines the name of the global animation that will be run on all nodes
  49411. * @param node defines the root node where the animation will take place
  49412. * @param targetProperty defines property to animate
  49413. * @param framePerSecond defines the number of frame per second yo use
  49414. * @param totalFrame defines the number of frames in total
  49415. * @param from defines the initial value
  49416. * @param to defines the final value
  49417. * @param loopMode defines which loop mode you want to use (off by default)
  49418. * @param easingFunction defines the easing function to use (linear by default)
  49419. * @param onAnimationEnd defines the callback to call when animation end
  49420. * @returns the animatable created for this animation
  49421. */
  49422. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49423. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49424. if (!animation) {
  49425. return null;
  49426. }
  49427. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49428. };
  49429. /**
  49430. * Create and start an animation on a node and its descendants
  49431. * @param name defines the name of the global animation that will be run on all nodes
  49432. * @param node defines the root node where the animation will take place
  49433. * @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
  49434. * @param targetProperty defines property to animate
  49435. * @param framePerSecond defines the number of frame per second to use
  49436. * @param totalFrame defines the number of frames in total
  49437. * @param from defines the initial value
  49438. * @param to defines the final value
  49439. * @param loopMode defines which loop mode you want to use (off by default)
  49440. * @param easingFunction defines the easing function to use (linear by default)
  49441. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49442. * @returns the list of animatables created for all nodes
  49443. * @example https://www.babylonjs-playground.com/#MH0VLI
  49444. */
  49445. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49446. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49447. if (!animation) {
  49448. return null;
  49449. }
  49450. var scene = node.getScene();
  49451. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49452. };
  49453. /**
  49454. * Creates a new animation, merges it with the existing animations and starts it
  49455. * @param name Name of the animation
  49456. * @param node Node which contains the scene that begins the animations
  49457. * @param targetProperty Specifies which property to animate
  49458. * @param framePerSecond The frames per second of the animation
  49459. * @param totalFrame The total number of frames
  49460. * @param from The frame at the beginning of the animation
  49461. * @param to The frame at the end of the animation
  49462. * @param loopMode Specifies the loop mode of the animation
  49463. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49464. * @param onAnimationEnd Callback to run once the animation is complete
  49465. * @returns Nullable animation
  49466. */
  49467. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49468. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49469. if (!animation) {
  49470. return null;
  49471. }
  49472. node.animations.push(animation);
  49473. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49474. };
  49475. /**
  49476. * Transition property of an host to the target Value
  49477. * @param property The property to transition
  49478. * @param targetValue The target Value of the property
  49479. * @param host The object where the property to animate belongs
  49480. * @param scene Scene used to run the animation
  49481. * @param frameRate Framerate (in frame/s) to use
  49482. * @param transition The transition type we want to use
  49483. * @param duration The duration of the animation, in milliseconds
  49484. * @param onAnimationEnd Callback trigger at the end of the animation
  49485. * @returns Nullable animation
  49486. */
  49487. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49488. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49489. if (duration <= 0) {
  49490. host[property] = targetValue;
  49491. if (onAnimationEnd) {
  49492. onAnimationEnd();
  49493. }
  49494. return null;
  49495. }
  49496. var endFrame = frameRate * (duration / 1000);
  49497. transition.setKeys([{
  49498. frame: 0,
  49499. value: host[property].clone ? host[property].clone() : host[property]
  49500. },
  49501. {
  49502. frame: endFrame,
  49503. value: targetValue
  49504. }]);
  49505. if (!host.animations) {
  49506. host.animations = [];
  49507. }
  49508. host.animations.push(transition);
  49509. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49510. animation.onAnimationEnd = onAnimationEnd;
  49511. return animation;
  49512. };
  49513. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49514. /**
  49515. * Return the array of runtime animations currently using this animation
  49516. */
  49517. get: function () {
  49518. return this._runtimeAnimations;
  49519. },
  49520. enumerable: true,
  49521. configurable: true
  49522. });
  49523. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49524. /**
  49525. * Specifies if any of the runtime animations are currently running
  49526. */
  49527. get: function () {
  49528. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49529. var runtimeAnimation = _a[_i];
  49530. if (!runtimeAnimation.isStopped) {
  49531. return true;
  49532. }
  49533. }
  49534. return false;
  49535. },
  49536. enumerable: true,
  49537. configurable: true
  49538. });
  49539. // Methods
  49540. /**
  49541. * Converts the animation to a string
  49542. * @param fullDetails support for multiple levels of logging within scene loading
  49543. * @returns String form of the animation
  49544. */
  49545. Animation.prototype.toString = function (fullDetails) {
  49546. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49547. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49548. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49549. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49550. if (fullDetails) {
  49551. ret += ", Ranges: {";
  49552. var first = true;
  49553. for (var name in this._ranges) {
  49554. if (first) {
  49555. ret += ", ";
  49556. first = false;
  49557. }
  49558. ret += name;
  49559. }
  49560. ret += "}";
  49561. }
  49562. return ret;
  49563. };
  49564. /**
  49565. * Add an event to this animation
  49566. * @param event Event to add
  49567. */
  49568. Animation.prototype.addEvent = function (event) {
  49569. this._events.push(event);
  49570. };
  49571. /**
  49572. * Remove all events found at the given frame
  49573. * @param frame The frame to remove events from
  49574. */
  49575. Animation.prototype.removeEvents = function (frame) {
  49576. for (var index = 0; index < this._events.length; index++) {
  49577. if (this._events[index].frame === frame) {
  49578. this._events.splice(index, 1);
  49579. index--;
  49580. }
  49581. }
  49582. };
  49583. /**
  49584. * Retrieves all the events from the animation
  49585. * @returns Events from the animation
  49586. */
  49587. Animation.prototype.getEvents = function () {
  49588. return this._events;
  49589. };
  49590. /**
  49591. * Creates an animation range
  49592. * @param name Name of the animation range
  49593. * @param from Starting frame of the animation range
  49594. * @param to Ending frame of the animation
  49595. */
  49596. Animation.prototype.createRange = function (name, from, to) {
  49597. // check name not already in use; could happen for bones after serialized
  49598. if (!this._ranges[name]) {
  49599. this._ranges[name] = new AnimationRange(name, from, to);
  49600. }
  49601. };
  49602. /**
  49603. * Deletes an animation range by name
  49604. * @param name Name of the animation range to delete
  49605. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49606. */
  49607. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49608. if (deleteFrames === void 0) { deleteFrames = true; }
  49609. var range = this._ranges[name];
  49610. if (!range) {
  49611. return;
  49612. }
  49613. if (deleteFrames) {
  49614. var from = range.from;
  49615. var to = range.to;
  49616. // this loop MUST go high to low for multiple splices to work
  49617. for (var key = this._keys.length - 1; key >= 0; key--) {
  49618. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49619. this._keys.splice(key, 1);
  49620. }
  49621. }
  49622. }
  49623. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49624. };
  49625. /**
  49626. * Gets the animation range by name, or null if not defined
  49627. * @param name Name of the animation range
  49628. * @returns Nullable animation range
  49629. */
  49630. Animation.prototype.getRange = function (name) {
  49631. return this._ranges[name];
  49632. };
  49633. /**
  49634. * Gets the key frames from the animation
  49635. * @returns The key frames of the animation
  49636. */
  49637. Animation.prototype.getKeys = function () {
  49638. return this._keys;
  49639. };
  49640. /**
  49641. * Gets the highest frame rate of the animation
  49642. * @returns Highest frame rate of the animation
  49643. */
  49644. Animation.prototype.getHighestFrame = function () {
  49645. var ret = 0;
  49646. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49647. if (ret < this._keys[key].frame) {
  49648. ret = this._keys[key].frame;
  49649. }
  49650. }
  49651. return ret;
  49652. };
  49653. /**
  49654. * Gets the easing function of the animation
  49655. * @returns Easing function of the animation
  49656. */
  49657. Animation.prototype.getEasingFunction = function () {
  49658. return this._easingFunction;
  49659. };
  49660. /**
  49661. * Sets the easing function of the animation
  49662. * @param easingFunction A custom mathematical formula for animation
  49663. */
  49664. Animation.prototype.setEasingFunction = function (easingFunction) {
  49665. this._easingFunction = easingFunction;
  49666. };
  49667. /**
  49668. * Interpolates a scalar linearly
  49669. * @param startValue Start value of the animation curve
  49670. * @param endValue End value of the animation curve
  49671. * @param gradient Scalar amount to interpolate
  49672. * @returns Interpolated scalar value
  49673. */
  49674. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49675. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49676. };
  49677. /**
  49678. * Interpolates a scalar cubically
  49679. * @param startValue Start value of the animation curve
  49680. * @param outTangent End tangent of the animation
  49681. * @param endValue End value of the animation curve
  49682. * @param inTangent Start tangent of the animation curve
  49683. * @param gradient Scalar amount to interpolate
  49684. * @returns Interpolated scalar value
  49685. */
  49686. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49687. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49688. };
  49689. /**
  49690. * Interpolates a quaternion using a spherical linear interpolation
  49691. * @param startValue Start value of the animation curve
  49692. * @param endValue End value of the animation curve
  49693. * @param gradient Scalar amount to interpolate
  49694. * @returns Interpolated quaternion value
  49695. */
  49696. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49697. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49698. };
  49699. /**
  49700. * Interpolates a quaternion cubically
  49701. * @param startValue Start value of the animation curve
  49702. * @param outTangent End tangent of the animation curve
  49703. * @param endValue End value of the animation curve
  49704. * @param inTangent Start tangent of the animation curve
  49705. * @param gradient Scalar amount to interpolate
  49706. * @returns Interpolated quaternion value
  49707. */
  49708. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49709. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49710. };
  49711. /**
  49712. * Interpolates a Vector3 linearl
  49713. * @param startValue Start value of the animation curve
  49714. * @param endValue End value of the animation curve
  49715. * @param gradient Scalar amount to interpolate
  49716. * @returns Interpolated scalar value
  49717. */
  49718. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49719. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49720. };
  49721. /**
  49722. * Interpolates a Vector3 cubically
  49723. * @param startValue Start value of the animation curve
  49724. * @param outTangent End tangent of the animation
  49725. * @param endValue End value of the animation curve
  49726. * @param inTangent Start tangent of the animation curve
  49727. * @param gradient Scalar amount to interpolate
  49728. * @returns InterpolatedVector3 value
  49729. */
  49730. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49731. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49732. };
  49733. /**
  49734. * Interpolates a Vector2 linearly
  49735. * @param startValue Start value of the animation curve
  49736. * @param endValue End value of the animation curve
  49737. * @param gradient Scalar amount to interpolate
  49738. * @returns Interpolated Vector2 value
  49739. */
  49740. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49741. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49742. };
  49743. /**
  49744. * Interpolates a Vector2 cubically
  49745. * @param startValue Start value of the animation curve
  49746. * @param outTangent End tangent of the animation
  49747. * @param endValue End value of the animation curve
  49748. * @param inTangent Start tangent of the animation curve
  49749. * @param gradient Scalar amount to interpolate
  49750. * @returns Interpolated Vector2 value
  49751. */
  49752. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49753. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49754. };
  49755. /**
  49756. * Interpolates a size linearly
  49757. * @param startValue Start value of the animation curve
  49758. * @param endValue End value of the animation curve
  49759. * @param gradient Scalar amount to interpolate
  49760. * @returns Interpolated Size value
  49761. */
  49762. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49763. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49764. };
  49765. /**
  49766. * Interpolates a Color3 linearly
  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 Color3 value
  49771. */
  49772. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49773. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49774. };
  49775. /**
  49776. * @hidden Internal use only
  49777. */
  49778. Animation.prototype._getKeyValue = function (value) {
  49779. if (typeof value === "function") {
  49780. return value();
  49781. }
  49782. return value;
  49783. };
  49784. /**
  49785. * @hidden Internal use only
  49786. */
  49787. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49788. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49789. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49790. }
  49791. var keys = this.getKeys();
  49792. // Try to get a hash to find the right key
  49793. 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));
  49794. if (keys[startKeyIndex].frame >= currentFrame) {
  49795. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49796. startKeyIndex--;
  49797. }
  49798. }
  49799. for (var key = startKeyIndex; key < keys.length; key++) {
  49800. var endKey = keys[key + 1];
  49801. if (endKey.frame >= currentFrame) {
  49802. var startKey = keys[key];
  49803. var startValue = this._getKeyValue(startKey.value);
  49804. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49805. return startValue;
  49806. }
  49807. var endValue = this._getKeyValue(endKey.value);
  49808. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49809. var frameDelta = endKey.frame - startKey.frame;
  49810. // gradient : percent of currentFrame between the frame inf and the frame sup
  49811. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49812. // check for easingFunction and correction of gradient
  49813. var easingFunction = this.getEasingFunction();
  49814. if (easingFunction != null) {
  49815. gradient = easingFunction.ease(gradient);
  49816. }
  49817. switch (this.dataType) {
  49818. // Float
  49819. case Animation.ANIMATIONTYPE_FLOAT:
  49820. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49821. switch (loopMode) {
  49822. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49823. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49824. return floatValue;
  49825. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49826. return offsetValue * repeatCount + floatValue;
  49827. }
  49828. break;
  49829. // Quaternion
  49830. case Animation.ANIMATIONTYPE_QUATERNION:
  49831. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49832. switch (loopMode) {
  49833. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49834. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49835. return quatValue;
  49836. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49837. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49838. }
  49839. return quatValue;
  49840. // Vector3
  49841. case Animation.ANIMATIONTYPE_VECTOR3:
  49842. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49843. switch (loopMode) {
  49844. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49845. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49846. return vec3Value;
  49847. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49848. return vec3Value.add(offsetValue.scale(repeatCount));
  49849. }
  49850. // Vector2
  49851. case Animation.ANIMATIONTYPE_VECTOR2:
  49852. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49853. switch (loopMode) {
  49854. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49855. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49856. return vec2Value;
  49857. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49858. return vec2Value.add(offsetValue.scale(repeatCount));
  49859. }
  49860. // Size
  49861. case Animation.ANIMATIONTYPE_SIZE:
  49862. switch (loopMode) {
  49863. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49864. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49865. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49866. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49867. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49868. }
  49869. // Color3
  49870. case Animation.ANIMATIONTYPE_COLOR3:
  49871. switch (loopMode) {
  49872. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49873. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49874. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49875. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49876. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49877. }
  49878. // Matrix
  49879. case Animation.ANIMATIONTYPE_MATRIX:
  49880. switch (loopMode) {
  49881. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49882. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49883. if (Animation.AllowMatricesInterpolation) {
  49884. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49885. }
  49886. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49887. return startValue;
  49888. }
  49889. default:
  49890. break;
  49891. }
  49892. break;
  49893. }
  49894. }
  49895. return this._getKeyValue(keys[keys.length - 1].value);
  49896. };
  49897. /**
  49898. * Defines the function to use to interpolate matrices
  49899. * @param startValue defines the start matrix
  49900. * @param endValue defines the end matrix
  49901. * @param gradient defines the gradient between both matrices
  49902. * @param result defines an optional target matrix where to store the interpolation
  49903. * @returns the interpolated matrix
  49904. */
  49905. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49906. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49907. if (result) {
  49908. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49909. return result;
  49910. }
  49911. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49912. }
  49913. if (result) {
  49914. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49915. return result;
  49916. }
  49917. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49918. };
  49919. /**
  49920. * Makes a copy of the animation
  49921. * @returns Cloned animation
  49922. */
  49923. Animation.prototype.clone = function () {
  49924. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49925. clone.enableBlending = this.enableBlending;
  49926. clone.blendingSpeed = this.blendingSpeed;
  49927. if (this._keys) {
  49928. clone.setKeys(this._keys);
  49929. }
  49930. if (this._ranges) {
  49931. clone._ranges = {};
  49932. for (var name in this._ranges) {
  49933. var range = this._ranges[name];
  49934. if (!range) {
  49935. continue;
  49936. }
  49937. clone._ranges[name] = range.clone();
  49938. }
  49939. }
  49940. return clone;
  49941. };
  49942. /**
  49943. * Sets the key frames of the animation
  49944. * @param values The animation key frames to set
  49945. */
  49946. Animation.prototype.setKeys = function (values) {
  49947. this._keys = values.slice(0);
  49948. };
  49949. /**
  49950. * Serializes the animation to an object
  49951. * @returns Serialized object
  49952. */
  49953. Animation.prototype.serialize = function () {
  49954. var serializationObject = {};
  49955. serializationObject.name = this.name;
  49956. serializationObject.property = this.targetProperty;
  49957. serializationObject.framePerSecond = this.framePerSecond;
  49958. serializationObject.dataType = this.dataType;
  49959. serializationObject.loopBehavior = this.loopMode;
  49960. serializationObject.enableBlending = this.enableBlending;
  49961. serializationObject.blendingSpeed = this.blendingSpeed;
  49962. var dataType = this.dataType;
  49963. serializationObject.keys = [];
  49964. var keys = this.getKeys();
  49965. for (var index = 0; index < keys.length; index++) {
  49966. var animationKey = keys[index];
  49967. var key = {};
  49968. key.frame = animationKey.frame;
  49969. switch (dataType) {
  49970. case Animation.ANIMATIONTYPE_FLOAT:
  49971. key.values = [animationKey.value];
  49972. break;
  49973. case Animation.ANIMATIONTYPE_QUATERNION:
  49974. case Animation.ANIMATIONTYPE_MATRIX:
  49975. case Animation.ANIMATIONTYPE_VECTOR3:
  49976. case Animation.ANIMATIONTYPE_COLOR3:
  49977. key.values = animationKey.value.asArray();
  49978. break;
  49979. }
  49980. serializationObject.keys.push(key);
  49981. }
  49982. serializationObject.ranges = [];
  49983. for (var name in this._ranges) {
  49984. var source = this._ranges[name];
  49985. if (!source) {
  49986. continue;
  49987. }
  49988. var range = {};
  49989. range.name = name;
  49990. range.from = source.from;
  49991. range.to = source.to;
  49992. serializationObject.ranges.push(range);
  49993. }
  49994. return serializationObject;
  49995. };
  49996. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49997. /**
  49998. * Get the float animation type
  49999. */
  50000. get: function () {
  50001. return Animation._ANIMATIONTYPE_FLOAT;
  50002. },
  50003. enumerable: true,
  50004. configurable: true
  50005. });
  50006. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50007. /**
  50008. * Get the Vector3 animation type
  50009. */
  50010. get: function () {
  50011. return Animation._ANIMATIONTYPE_VECTOR3;
  50012. },
  50013. enumerable: true,
  50014. configurable: true
  50015. });
  50016. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50017. /**
  50018. * Get the Vectpr2 animation type
  50019. */
  50020. get: function () {
  50021. return Animation._ANIMATIONTYPE_VECTOR2;
  50022. },
  50023. enumerable: true,
  50024. configurable: true
  50025. });
  50026. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50027. /**
  50028. * Get the Size animation type
  50029. */
  50030. get: function () {
  50031. return Animation._ANIMATIONTYPE_SIZE;
  50032. },
  50033. enumerable: true,
  50034. configurable: true
  50035. });
  50036. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50037. /**
  50038. * Get the Quaternion animation type
  50039. */
  50040. get: function () {
  50041. return Animation._ANIMATIONTYPE_QUATERNION;
  50042. },
  50043. enumerable: true,
  50044. configurable: true
  50045. });
  50046. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50047. /**
  50048. * Get the Matrix animation type
  50049. */
  50050. get: function () {
  50051. return Animation._ANIMATIONTYPE_MATRIX;
  50052. },
  50053. enumerable: true,
  50054. configurable: true
  50055. });
  50056. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50057. /**
  50058. * Get the Color3 animation type
  50059. */
  50060. get: function () {
  50061. return Animation._ANIMATIONTYPE_COLOR3;
  50062. },
  50063. enumerable: true,
  50064. configurable: true
  50065. });
  50066. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50067. /**
  50068. * Get the Relative Loop Mode
  50069. */
  50070. get: function () {
  50071. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50072. },
  50073. enumerable: true,
  50074. configurable: true
  50075. });
  50076. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50077. /**
  50078. * Get the Cycle Loop Mode
  50079. */
  50080. get: function () {
  50081. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50082. },
  50083. enumerable: true,
  50084. configurable: true
  50085. });
  50086. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50087. /**
  50088. * Get the Constant Loop Mode
  50089. */
  50090. get: function () {
  50091. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50092. },
  50093. enumerable: true,
  50094. configurable: true
  50095. });
  50096. /** @hidden */
  50097. Animation._UniversalLerp = function (left, right, amount) {
  50098. var constructor = left.constructor;
  50099. if (constructor.Lerp) { // Lerp supported
  50100. return constructor.Lerp(left, right, amount);
  50101. }
  50102. else if (constructor.Slerp) { // Slerp supported
  50103. return constructor.Slerp(left, right, amount);
  50104. }
  50105. else if (left.toFixed) { // Number
  50106. return left * (1.0 - amount) + amount * right;
  50107. }
  50108. else { // Blending not supported
  50109. return right;
  50110. }
  50111. };
  50112. /**
  50113. * Parses an animation object and creates an animation
  50114. * @param parsedAnimation Parsed animation object
  50115. * @returns Animation object
  50116. */
  50117. Animation.Parse = function (parsedAnimation) {
  50118. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50119. var dataType = parsedAnimation.dataType;
  50120. var keys = [];
  50121. var data;
  50122. var index;
  50123. if (parsedAnimation.enableBlending) {
  50124. animation.enableBlending = parsedAnimation.enableBlending;
  50125. }
  50126. if (parsedAnimation.blendingSpeed) {
  50127. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50128. }
  50129. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50130. var key = parsedAnimation.keys[index];
  50131. var inTangent;
  50132. var outTangent;
  50133. switch (dataType) {
  50134. case Animation.ANIMATIONTYPE_FLOAT:
  50135. data = key.values[0];
  50136. if (key.values.length >= 1) {
  50137. inTangent = key.values[1];
  50138. }
  50139. if (key.values.length >= 2) {
  50140. outTangent = key.values[2];
  50141. }
  50142. break;
  50143. case Animation.ANIMATIONTYPE_QUATERNION:
  50144. data = BABYLON.Quaternion.FromArray(key.values);
  50145. if (key.values.length >= 8) {
  50146. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50147. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50148. inTangent = _inTangent;
  50149. }
  50150. }
  50151. if (key.values.length >= 12) {
  50152. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50153. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50154. outTangent = _outTangent;
  50155. }
  50156. }
  50157. break;
  50158. case Animation.ANIMATIONTYPE_MATRIX:
  50159. data = BABYLON.Matrix.FromArray(key.values);
  50160. break;
  50161. case Animation.ANIMATIONTYPE_COLOR3:
  50162. data = BABYLON.Color3.FromArray(key.values);
  50163. break;
  50164. case Animation.ANIMATIONTYPE_VECTOR3:
  50165. default:
  50166. data = BABYLON.Vector3.FromArray(key.values);
  50167. break;
  50168. }
  50169. var keyData = {};
  50170. keyData.frame = key.frame;
  50171. keyData.value = data;
  50172. if (inTangent != undefined) {
  50173. keyData.inTangent = inTangent;
  50174. }
  50175. if (outTangent != undefined) {
  50176. keyData.outTangent = outTangent;
  50177. }
  50178. keys.push(keyData);
  50179. }
  50180. animation.setKeys(keys);
  50181. if (parsedAnimation.ranges) {
  50182. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50183. data = parsedAnimation.ranges[index];
  50184. animation.createRange(data.name, data.from, data.to);
  50185. }
  50186. }
  50187. return animation;
  50188. };
  50189. /**
  50190. * Appends the serialized animations from the source animations
  50191. * @param source Source containing the animations
  50192. * @param destination Target to store the animations
  50193. */
  50194. Animation.AppendSerializedAnimations = function (source, destination) {
  50195. if (source.animations) {
  50196. destination.animations = [];
  50197. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50198. var animation = source.animations[animationIndex];
  50199. destination.animations.push(animation.serialize());
  50200. }
  50201. }
  50202. };
  50203. /**
  50204. * Use matrix interpolation instead of using direct key value when animating matrices
  50205. */
  50206. Animation.AllowMatricesInterpolation = false;
  50207. /**
  50208. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50209. */
  50210. Animation.AllowMatrixDecomposeForInterpolation = true;
  50211. // Statics
  50212. /**
  50213. * Float animation type
  50214. */
  50215. Animation._ANIMATIONTYPE_FLOAT = 0;
  50216. /**
  50217. * Vector3 animation type
  50218. */
  50219. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50220. /**
  50221. * Quaternion animation type
  50222. */
  50223. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50224. /**
  50225. * Matrix animation type
  50226. */
  50227. Animation._ANIMATIONTYPE_MATRIX = 3;
  50228. /**
  50229. * Color3 animation type
  50230. */
  50231. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50232. /**
  50233. * Vector2 animation type
  50234. */
  50235. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50236. /**
  50237. * Size animation type
  50238. */
  50239. Animation._ANIMATIONTYPE_SIZE = 6;
  50240. /**
  50241. * Relative Loop Mode
  50242. */
  50243. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50244. /**
  50245. * Cycle Loop Mode
  50246. */
  50247. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50248. /**
  50249. * Constant Loop Mode
  50250. */
  50251. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50252. return Animation;
  50253. }());
  50254. BABYLON.Animation = Animation;
  50255. })(BABYLON || (BABYLON = {}));
  50256. //# sourceMappingURL=babylon.animation.js.map
  50257. var BABYLON;
  50258. (function (BABYLON) {
  50259. /**
  50260. * This class defines the direct association between an animation and a target
  50261. */
  50262. var TargetedAnimation = /** @class */ (function () {
  50263. function TargetedAnimation() {
  50264. }
  50265. return TargetedAnimation;
  50266. }());
  50267. BABYLON.TargetedAnimation = TargetedAnimation;
  50268. /**
  50269. * Use this class to create coordinated animations on multiple targets
  50270. */
  50271. var AnimationGroup = /** @class */ (function () {
  50272. function AnimationGroup(name, scene) {
  50273. if (scene === void 0) { scene = null; }
  50274. this.name = name;
  50275. this._targetedAnimations = new Array();
  50276. this._animatables = new Array();
  50277. this._from = Number.MAX_VALUE;
  50278. this._to = -Number.MAX_VALUE;
  50279. this._speedRatio = 1;
  50280. this.onAnimationEndObservable = new BABYLON.Observable();
  50281. /**
  50282. * This observable will notify when all animations have ended.
  50283. */
  50284. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50285. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50286. this._scene.animationGroups.push(this);
  50287. }
  50288. Object.defineProperty(AnimationGroup.prototype, "from", {
  50289. /**
  50290. * Gets the first frame
  50291. */
  50292. get: function () {
  50293. return this._from;
  50294. },
  50295. enumerable: true,
  50296. configurable: true
  50297. });
  50298. Object.defineProperty(AnimationGroup.prototype, "to", {
  50299. /**
  50300. * Gets the last frame
  50301. */
  50302. get: function () {
  50303. return this._to;
  50304. },
  50305. enumerable: true,
  50306. configurable: true
  50307. });
  50308. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50309. /**
  50310. * Define if the animations are started
  50311. */
  50312. get: function () {
  50313. return this._isStarted;
  50314. },
  50315. enumerable: true,
  50316. configurable: true
  50317. });
  50318. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50319. /**
  50320. * Gets or sets the speed ratio to use for all animations
  50321. */
  50322. get: function () {
  50323. return this._speedRatio;
  50324. },
  50325. /**
  50326. * Gets or sets the speed ratio to use for all animations
  50327. */
  50328. set: function (value) {
  50329. if (this._speedRatio === value) {
  50330. return;
  50331. }
  50332. this._speedRatio = value;
  50333. for (var index = 0; index < this._animatables.length; index++) {
  50334. var animatable = this._animatables[index];
  50335. animatable.speedRatio = this._speedRatio;
  50336. }
  50337. },
  50338. enumerable: true,
  50339. configurable: true
  50340. });
  50341. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50342. /**
  50343. * Gets the targeted animations for this animation group
  50344. */
  50345. get: function () {
  50346. return this._targetedAnimations;
  50347. },
  50348. enumerable: true,
  50349. configurable: true
  50350. });
  50351. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50352. /**
  50353. * returning the list of animatables controlled by this animation group.
  50354. */
  50355. get: function () {
  50356. return this._animatables;
  50357. },
  50358. enumerable: true,
  50359. configurable: true
  50360. });
  50361. /**
  50362. * Add an animation (with its target) in the group
  50363. * @param animation defines the animation we want to add
  50364. * @param target defines the target of the animation
  50365. * @returns the {BABYLON.TargetedAnimation} object
  50366. */
  50367. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50368. var targetedAnimation = {
  50369. animation: animation,
  50370. target: target
  50371. };
  50372. var keys = animation.getKeys();
  50373. if (this._from > keys[0].frame) {
  50374. this._from = keys[0].frame;
  50375. }
  50376. if (this._to < keys[keys.length - 1].frame) {
  50377. this._to = keys[keys.length - 1].frame;
  50378. }
  50379. this._targetedAnimations.push(targetedAnimation);
  50380. return targetedAnimation;
  50381. };
  50382. /**
  50383. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50384. * It can add constant keys at begin or end
  50385. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50386. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50387. */
  50388. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50389. if (beginFrame === void 0) { beginFrame = null; }
  50390. if (endFrame === void 0) { endFrame = null; }
  50391. if (beginFrame == null)
  50392. beginFrame = this._from;
  50393. if (endFrame == null)
  50394. endFrame = this._to;
  50395. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50396. var targetedAnimation = this._targetedAnimations[index];
  50397. var keys = targetedAnimation.animation.getKeys();
  50398. var startKey = keys[0];
  50399. var endKey = keys[keys.length - 1];
  50400. if (startKey.frame > beginFrame) {
  50401. var newKey = {
  50402. frame: beginFrame,
  50403. value: startKey.value,
  50404. inTangent: startKey.inTangent,
  50405. outTangent: startKey.outTangent,
  50406. interpolation: startKey.interpolation
  50407. };
  50408. keys.splice(0, 0, newKey);
  50409. }
  50410. if (endKey.frame < endFrame) {
  50411. var newKey = {
  50412. frame: endFrame,
  50413. value: endKey.value,
  50414. inTangent: endKey.outTangent,
  50415. outTangent: endKey.outTangent,
  50416. interpolation: endKey.interpolation
  50417. };
  50418. keys.push(newKey);
  50419. }
  50420. }
  50421. this._from = beginFrame;
  50422. this._to = endFrame;
  50423. return this;
  50424. };
  50425. /**
  50426. * Start all animations on given targets
  50427. * @param loop defines if animations must loop
  50428. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50429. * @param from defines the from key (optional)
  50430. * @param to defines the to key (optional)
  50431. * @returns the current animation group
  50432. */
  50433. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50434. var _this = this;
  50435. if (loop === void 0) { loop = false; }
  50436. if (speedRatio === void 0) { speedRatio = 1; }
  50437. if (this._isStarted || this._targetedAnimations.length === 0) {
  50438. return this;
  50439. }
  50440. var _loop_1 = function (targetedAnimation) {
  50441. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50442. animatable.onAnimationEnd = function () {
  50443. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50444. _this._checkAnimationGroupEnded(animatable);
  50445. };
  50446. this_1._animatables.push(animatable);
  50447. };
  50448. var this_1 = this;
  50449. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50450. var targetedAnimation = _a[_i];
  50451. _loop_1(targetedAnimation);
  50452. }
  50453. this._speedRatio = speedRatio;
  50454. this._isStarted = true;
  50455. return this;
  50456. };
  50457. /**
  50458. * Pause all animations
  50459. */
  50460. AnimationGroup.prototype.pause = function () {
  50461. if (!this._isStarted) {
  50462. return this;
  50463. }
  50464. for (var index = 0; index < this._animatables.length; index++) {
  50465. var animatable = this._animatables[index];
  50466. animatable.pause();
  50467. }
  50468. return this;
  50469. };
  50470. /**
  50471. * Play all animations to initial state
  50472. * This function will start() the animations if they were not started or will restart() them if they were paused
  50473. * @param loop defines if animations must loop
  50474. */
  50475. AnimationGroup.prototype.play = function (loop) {
  50476. // only if all animatables are ready and exist
  50477. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50478. if (loop !== undefined) {
  50479. for (var index = 0; index < this._animatables.length; index++) {
  50480. var animatable = this._animatables[index];
  50481. animatable.loopAnimation = loop;
  50482. }
  50483. }
  50484. this.restart();
  50485. }
  50486. else {
  50487. this.stop();
  50488. this.start(loop, this._speedRatio);
  50489. }
  50490. return this;
  50491. };
  50492. /**
  50493. * Reset all animations to initial state
  50494. */
  50495. AnimationGroup.prototype.reset = function () {
  50496. if (!this._isStarted) {
  50497. return this;
  50498. }
  50499. for (var index = 0; index < this._animatables.length; index++) {
  50500. var animatable = this._animatables[index];
  50501. animatable.reset();
  50502. }
  50503. return this;
  50504. };
  50505. /**
  50506. * Restart animations from key 0
  50507. */
  50508. AnimationGroup.prototype.restart = function () {
  50509. if (!this._isStarted) {
  50510. return this;
  50511. }
  50512. for (var index = 0; index < this._animatables.length; index++) {
  50513. var animatable = this._animatables[index];
  50514. animatable.restart();
  50515. }
  50516. return this;
  50517. };
  50518. /**
  50519. * Stop all animations
  50520. */
  50521. AnimationGroup.prototype.stop = function () {
  50522. if (!this._isStarted) {
  50523. return this;
  50524. }
  50525. var list = this._animatables.slice();
  50526. for (var index = 0; index < list.length; index++) {
  50527. list[index].stop();
  50528. }
  50529. this._isStarted = false;
  50530. return this;
  50531. };
  50532. /**
  50533. * Set animation weight for all animatables
  50534. * @param weight defines the weight to use
  50535. * @return the animationGroup
  50536. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50537. */
  50538. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50539. for (var index = 0; index < this._animatables.length; index++) {
  50540. var animatable = this._animatables[index];
  50541. animatable.weight = weight;
  50542. }
  50543. return this;
  50544. };
  50545. /**
  50546. * Synchronize and normalize all animatables with a source animatable
  50547. * @param root defines the root animatable to synchronize with
  50548. * @return the animationGroup
  50549. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50550. */
  50551. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50552. for (var index = 0; index < this._animatables.length; index++) {
  50553. var animatable = this._animatables[index];
  50554. animatable.syncWith(root);
  50555. }
  50556. return this;
  50557. };
  50558. /**
  50559. * Goes to a specific frame in this animation group
  50560. * @param frame the frame number to go to
  50561. * @return the animationGroup
  50562. */
  50563. AnimationGroup.prototype.goToFrame = function (frame) {
  50564. if (!this._isStarted) {
  50565. return this;
  50566. }
  50567. for (var index = 0; index < this._animatables.length; index++) {
  50568. var animatable = this._animatables[index];
  50569. animatable.goToFrame(frame);
  50570. }
  50571. return this;
  50572. };
  50573. /**
  50574. * Dispose all associated resources
  50575. */
  50576. AnimationGroup.prototype.dispose = function () {
  50577. this._targetedAnimations = [];
  50578. this._animatables = [];
  50579. var index = this._scene.animationGroups.indexOf(this);
  50580. if (index > -1) {
  50581. this._scene.animationGroups.splice(index, 1);
  50582. }
  50583. };
  50584. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50585. // animatable should be taken out of the array
  50586. var idx = this._animatables.indexOf(animatable);
  50587. if (idx > -1) {
  50588. this._animatables.splice(idx, 1);
  50589. }
  50590. // all animatables were removed? animation group ended!
  50591. if (this._animatables.length === 0) {
  50592. this._isStarted = false;
  50593. this.onAnimationGroupEndObservable.notifyObservers(this);
  50594. }
  50595. };
  50596. return AnimationGroup;
  50597. }());
  50598. BABYLON.AnimationGroup = AnimationGroup;
  50599. })(BABYLON || (BABYLON = {}));
  50600. //# sourceMappingURL=babylon.animationGroup.js.map
  50601. var BABYLON;
  50602. (function (BABYLON) {
  50603. /**
  50604. * Defines a runtime animation
  50605. */
  50606. var RuntimeAnimation = /** @class */ (function () {
  50607. /**
  50608. * Create a new RuntimeAnimation object
  50609. * @param target defines the target of the animation
  50610. * @param animation defines the source animation object
  50611. * @param scene defines the hosting scene
  50612. * @param host defines the initiating Animatable
  50613. */
  50614. function RuntimeAnimation(target, animation, scene, host) {
  50615. var _this = this;
  50616. this._events = new Array();
  50617. /**
  50618. * The current frame of the runtime animation
  50619. */
  50620. this._currentFrame = 0;
  50621. /**
  50622. * The original value of the runtime animation
  50623. */
  50624. this._originalValue = new Array();
  50625. /**
  50626. * The offsets cache of the runtime animation
  50627. */
  50628. this._offsetsCache = {};
  50629. /**
  50630. * The high limits cache of the runtime animation
  50631. */
  50632. this._highLimitsCache = {};
  50633. /**
  50634. * Specifies if the runtime animation has been stopped
  50635. */
  50636. this._stopped = false;
  50637. /**
  50638. * The blending factor of the runtime animation
  50639. */
  50640. this._blendingFactor = 0;
  50641. /**
  50642. * The target path of the runtime animation
  50643. */
  50644. this._targetPath = "";
  50645. /**
  50646. * The weight of the runtime animation
  50647. */
  50648. this._weight = 1.0;
  50649. /**
  50650. * The ratio offset of the runtime animation
  50651. */
  50652. this._ratioOffset = 0;
  50653. /**
  50654. * The previous delay of the runtime animation
  50655. */
  50656. this._previousDelay = 0;
  50657. /**
  50658. * The previous ratio of the runtime animation
  50659. */
  50660. this._previousRatio = 0;
  50661. this._animation = animation;
  50662. this._target = target;
  50663. this._scene = scene;
  50664. this._host = host;
  50665. animation._runtimeAnimations.push(this);
  50666. // Cloning events locally
  50667. var events = animation.getEvents();
  50668. if (events && events.length > 0) {
  50669. events.forEach(function (e) {
  50670. _this._events.push(e._clone());
  50671. });
  50672. }
  50673. }
  50674. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50675. /**
  50676. * Gets the current frame of the runtime animation
  50677. */
  50678. get: function () {
  50679. return this._currentFrame;
  50680. },
  50681. enumerable: true,
  50682. configurable: true
  50683. });
  50684. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50685. /**
  50686. * Gets the weight of the runtime animation
  50687. */
  50688. get: function () {
  50689. return this._weight;
  50690. },
  50691. enumerable: true,
  50692. configurable: true
  50693. });
  50694. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50695. /**
  50696. * Gets the current value of the runtime animation
  50697. */
  50698. get: function () {
  50699. return this._currentValue;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50705. /**
  50706. * Gets the target path of the runtime animation
  50707. */
  50708. get: function () {
  50709. return this._targetPath;
  50710. },
  50711. enumerable: true,
  50712. configurable: true
  50713. });
  50714. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50715. /**
  50716. * Gets the actual target of the runtime animation
  50717. */
  50718. get: function () {
  50719. return this._activeTarget;
  50720. },
  50721. enumerable: true,
  50722. configurable: true
  50723. });
  50724. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50725. /**
  50726. * Gets the animation from the runtime animation
  50727. */
  50728. get: function () {
  50729. return this._animation;
  50730. },
  50731. enumerable: true,
  50732. configurable: true
  50733. });
  50734. /**
  50735. * Resets the runtime animation to the beginning
  50736. * @param restoreOriginal defines whether to restore the target property to the original value
  50737. */
  50738. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50739. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50740. if (restoreOriginal) {
  50741. if (this._target instanceof Array) {
  50742. var index = 0;
  50743. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50744. var target = _a[_i];
  50745. if (this._originalValue[index] !== undefined) {
  50746. this._setValue(target, this._originalValue[index], -1);
  50747. }
  50748. index++;
  50749. }
  50750. }
  50751. else {
  50752. if (this._originalValue[0] !== undefined) {
  50753. this._setValue(this._target, this._originalValue[0], -1);
  50754. }
  50755. }
  50756. }
  50757. this._offsetsCache = {};
  50758. this._highLimitsCache = {};
  50759. this._currentFrame = 0;
  50760. this._blendingFactor = 0;
  50761. this._originalValue = new Array();
  50762. // Events
  50763. for (var index = 0; index < this._events.length; index++) {
  50764. this._events[index].isDone = false;
  50765. }
  50766. };
  50767. /**
  50768. * Specifies if the runtime animation is stopped
  50769. * @returns Boolean specifying if the runtime animation is stopped
  50770. */
  50771. RuntimeAnimation.prototype.isStopped = function () {
  50772. return this._stopped;
  50773. };
  50774. /**
  50775. * Disposes of the runtime animation
  50776. */
  50777. RuntimeAnimation.prototype.dispose = function () {
  50778. var index = this._animation.runtimeAnimations.indexOf(this);
  50779. if (index > -1) {
  50780. this._animation.runtimeAnimations.splice(index, 1);
  50781. }
  50782. };
  50783. /**
  50784. * Interpolates the animation from the current frame
  50785. * @param currentFrame The frame to interpolate the animation to
  50786. * @param repeatCount The number of times that the animation should loop
  50787. * @param loopMode The type of looping mode to use
  50788. * @param offsetValue Animation offset value
  50789. * @param highLimitValue The high limit value
  50790. * @returns The interpolated value
  50791. */
  50792. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50793. this._currentFrame = currentFrame;
  50794. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50795. this._workValue = BABYLON.Matrix.Zero();
  50796. }
  50797. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50798. };
  50799. /**
  50800. * Apply the interpolated value to the target
  50801. * @param currentValue defines the value computed by the animation
  50802. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50803. */
  50804. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50805. if (weight === void 0) { weight = 1.0; }
  50806. if (this._target instanceof Array) {
  50807. var index = 0;
  50808. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50809. var target = _a[_i];
  50810. this._setValue(target, currentValue, weight, index);
  50811. index++;
  50812. }
  50813. }
  50814. else {
  50815. this._setValue(this._target, currentValue, weight);
  50816. }
  50817. };
  50818. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50819. if (targetIndex === void 0) { targetIndex = 0; }
  50820. // Set value
  50821. var path;
  50822. var destination;
  50823. var targetPropertyPath = this._animation.targetPropertyPath;
  50824. if (targetPropertyPath.length > 1) {
  50825. var property = target[targetPropertyPath[0]];
  50826. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50827. property = property[targetPropertyPath[index]];
  50828. }
  50829. path = targetPropertyPath[targetPropertyPath.length - 1];
  50830. destination = property;
  50831. }
  50832. else {
  50833. path = targetPropertyPath[0];
  50834. destination = target;
  50835. }
  50836. this._targetPath = path;
  50837. this._activeTarget = destination;
  50838. this._weight = weight;
  50839. if (this._originalValue[targetIndex] === undefined) {
  50840. var originalValue = void 0;
  50841. if (destination.getRestPose && path === "_matrix") { // For bones
  50842. originalValue = destination.getRestPose();
  50843. }
  50844. else {
  50845. originalValue = destination[path];
  50846. }
  50847. if (originalValue && originalValue.clone) {
  50848. this._originalValue[targetIndex] = originalValue.clone();
  50849. }
  50850. else {
  50851. this._originalValue[targetIndex] = originalValue;
  50852. }
  50853. }
  50854. // Blending
  50855. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50856. if (enableBlending && this._blendingFactor <= 1.0) {
  50857. if (!this._originalBlendValue) {
  50858. var originalValue = destination[path];
  50859. if (originalValue.clone) {
  50860. this._originalBlendValue = originalValue.clone();
  50861. }
  50862. else {
  50863. this._originalBlendValue = originalValue;
  50864. }
  50865. }
  50866. if (this._originalBlendValue.m) { // Matrix
  50867. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50868. if (this._currentValue) {
  50869. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50870. }
  50871. else {
  50872. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50873. }
  50874. }
  50875. else {
  50876. if (this._currentValue) {
  50877. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50878. }
  50879. else {
  50880. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50881. }
  50882. }
  50883. }
  50884. else {
  50885. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50886. }
  50887. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50888. this._blendingFactor += blendingSpeed;
  50889. }
  50890. else {
  50891. this._currentValue = currentValue;
  50892. }
  50893. if (weight !== -1.0) {
  50894. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50895. }
  50896. else {
  50897. destination[path] = this._currentValue;
  50898. }
  50899. if (target.markAsDirty) {
  50900. target.markAsDirty(this._animation.targetProperty);
  50901. }
  50902. };
  50903. /**
  50904. * Gets the loop pmode of the runtime animation
  50905. * @returns Loop Mode
  50906. */
  50907. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50908. if (this._target && this._target.animationPropertiesOverride) {
  50909. return this._target.animationPropertiesOverride.loopMode;
  50910. }
  50911. return this._animation.loopMode;
  50912. };
  50913. /**
  50914. * Move the current animation to a given frame
  50915. * @param frame defines the frame to move to
  50916. */
  50917. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50918. var keys = this._animation.getKeys();
  50919. if (frame < keys[0].frame) {
  50920. frame = keys[0].frame;
  50921. }
  50922. else if (frame > keys[keys.length - 1].frame) {
  50923. frame = keys[keys.length - 1].frame;
  50924. }
  50925. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50926. this.setValue(currentValue, -1);
  50927. };
  50928. /**
  50929. * @hidden Internal use only
  50930. */
  50931. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50932. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50933. this._ratioOffset = this._previousRatio - newRatio;
  50934. };
  50935. /**
  50936. * Execute the current animation
  50937. * @param delay defines the delay to add to the current frame
  50938. * @param from defines the lower bound of the animation range
  50939. * @param to defines the upper bound of the animation range
  50940. * @param loop defines if the current animation must loop
  50941. * @param speedRatio defines the current speed ratio
  50942. * @param weight defines the weight of the animation (default is -1 so no weight)
  50943. * @returns a boolean indicating if the animation is running
  50944. */
  50945. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50946. if (weight === void 0) { weight = -1.0; }
  50947. var targetPropertyPath = this._animation.targetPropertyPath;
  50948. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50949. this._stopped = true;
  50950. return false;
  50951. }
  50952. var returnValue = true;
  50953. var keys = this._animation.getKeys();
  50954. // Adding a start key at frame 0 if missing
  50955. if (keys[0].frame !== 0) {
  50956. var newKey = { frame: 0, value: keys[0].value };
  50957. keys.splice(0, 0, newKey);
  50958. }
  50959. // Adding a duplicate key when there is only one key at frame zero
  50960. else if (keys.length === 1) {
  50961. var newKey = { frame: 0.001, value: keys[0].value };
  50962. keys.push(newKey);
  50963. }
  50964. // Check limits
  50965. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50966. from = keys[0].frame;
  50967. }
  50968. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50969. to = keys[keys.length - 1].frame;
  50970. }
  50971. //to and from cannot be the same key
  50972. if (from === to) {
  50973. if (from > keys[0].frame) {
  50974. from--;
  50975. }
  50976. else if (to < keys[keys.length - 1].frame) {
  50977. to++;
  50978. }
  50979. }
  50980. // Compute ratio
  50981. var range = to - from;
  50982. var offsetValue;
  50983. // ratio represents the frame delta between from and to
  50984. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50985. var highLimitValue = 0;
  50986. this._previousDelay = delay;
  50987. this._previousRatio = ratio;
  50988. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50989. returnValue = false;
  50990. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50991. }
  50992. else {
  50993. // Get max value if required
  50994. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50995. var keyOffset = to.toString() + from.toString();
  50996. if (!this._offsetsCache[keyOffset]) {
  50997. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50998. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50999. switch (this._animation.dataType) {
  51000. // Float
  51001. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51002. this._offsetsCache[keyOffset] = toValue - fromValue;
  51003. break;
  51004. // Quaternion
  51005. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51006. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51007. break;
  51008. // Vector3
  51009. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51010. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51011. // Vector2
  51012. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51013. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51014. // Size
  51015. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51016. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51017. // Color3
  51018. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51019. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51020. default:
  51021. break;
  51022. }
  51023. this._highLimitsCache[keyOffset] = toValue;
  51024. }
  51025. highLimitValue = this._highLimitsCache[keyOffset];
  51026. offsetValue = this._offsetsCache[keyOffset];
  51027. }
  51028. }
  51029. if (offsetValue === undefined) {
  51030. switch (this._animation.dataType) {
  51031. // Float
  51032. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51033. offsetValue = 0;
  51034. break;
  51035. // Quaternion
  51036. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51037. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51038. break;
  51039. // Vector3
  51040. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51041. offsetValue = BABYLON.Vector3.Zero();
  51042. break;
  51043. // Vector2
  51044. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51045. offsetValue = BABYLON.Vector2.Zero();
  51046. break;
  51047. // Size
  51048. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51049. offsetValue = BABYLON.Size.Zero();
  51050. break;
  51051. // Color3
  51052. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51053. offsetValue = BABYLON.Color3.Black();
  51054. }
  51055. }
  51056. // Compute value
  51057. var repeatCount = (ratio / range) >> 0;
  51058. var currentFrame = returnValue ? from + ratio % range : to;
  51059. // Need to normalize?
  51060. if (this._host && this._host.syncRoot) {
  51061. var syncRoot = this._host.syncRoot;
  51062. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51063. currentFrame = from + (to - from) * hostNormalizedFrame;
  51064. }
  51065. // Reset events if looping
  51066. var events = this._events;
  51067. if (range > 0 && this.currentFrame > currentFrame ||
  51068. range < 0 && this.currentFrame < currentFrame) {
  51069. // Need to reset animation events
  51070. for (var index = 0; index < events.length; index++) {
  51071. if (!events[index].onlyOnce) {
  51072. // reset event, the animation is looping
  51073. events[index].isDone = false;
  51074. }
  51075. }
  51076. }
  51077. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51078. // Set value
  51079. this.setValue(currentValue, weight);
  51080. // Check events
  51081. for (var index = 0; index < events.length; index++) {
  51082. // Make sure current frame has passed event frame and that event frame is within the current range
  51083. // Also, handle both forward and reverse animations
  51084. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51085. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51086. var event = events[index];
  51087. if (!event.isDone) {
  51088. // If event should be done only once, remove it.
  51089. if (event.onlyOnce) {
  51090. events.splice(index, 1);
  51091. index--;
  51092. }
  51093. event.isDone = true;
  51094. event.action();
  51095. } // Don't do anything if the event has already be done.
  51096. }
  51097. }
  51098. if (!returnValue) {
  51099. this._stopped = true;
  51100. }
  51101. return returnValue;
  51102. };
  51103. return RuntimeAnimation;
  51104. }());
  51105. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51106. })(BABYLON || (BABYLON = {}));
  51107. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51108. var BABYLON;
  51109. (function (BABYLON) {
  51110. /**
  51111. * Class used to store an actual running animation
  51112. */
  51113. var Animatable = /** @class */ (function () {
  51114. /**
  51115. * Creates a new Animatable
  51116. * @param scene defines the hosting scene
  51117. * @param target defines the target object
  51118. * @param fromFrame defines the starting frame number (default is 0)
  51119. * @param toFrame defines the ending frame number (default is 100)
  51120. * @param loopAnimation defines if the animation must loop (default is false)
  51121. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51122. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51123. * @param animations defines a group of animation to add to the new Animatable
  51124. */
  51125. function Animatable(scene,
  51126. /** defines the target object */
  51127. target,
  51128. /** defines the starting frame number (default is 0) */
  51129. fromFrame,
  51130. /** defines the ending frame number (default is 100) */
  51131. toFrame,
  51132. /** defines if the animation must loop (default is false) */
  51133. loopAnimation, speedRatio,
  51134. /** defines a callback to call when animation ends if it is not looping */
  51135. onAnimationEnd, animations) {
  51136. if (fromFrame === void 0) { fromFrame = 0; }
  51137. if (toFrame === void 0) { toFrame = 100; }
  51138. if (loopAnimation === void 0) { loopAnimation = false; }
  51139. if (speedRatio === void 0) { speedRatio = 1.0; }
  51140. this.target = target;
  51141. this.fromFrame = fromFrame;
  51142. this.toFrame = toFrame;
  51143. this.loopAnimation = loopAnimation;
  51144. this.onAnimationEnd = onAnimationEnd;
  51145. this._localDelayOffset = null;
  51146. this._pausedDelay = null;
  51147. this._runtimeAnimations = new Array();
  51148. this._paused = false;
  51149. this._speedRatio = 1;
  51150. this._weight = -1.0;
  51151. /**
  51152. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51153. * This will only apply for non looping animation (default is true)
  51154. */
  51155. this.disposeOnEnd = true;
  51156. /**
  51157. * Gets a boolean indicating if the animation has started
  51158. */
  51159. this.animationStarted = false;
  51160. /**
  51161. * Observer raised when the animation ends
  51162. */
  51163. this.onAnimationEndObservable = new BABYLON.Observable();
  51164. this._scene = scene;
  51165. if (animations) {
  51166. this.appendAnimations(target, animations);
  51167. }
  51168. this._speedRatio = speedRatio;
  51169. scene._activeAnimatables.push(this);
  51170. }
  51171. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51172. /**
  51173. * Gets the root Animatable used to synchronize and normalize animations
  51174. */
  51175. get: function () {
  51176. return this._syncRoot;
  51177. },
  51178. enumerable: true,
  51179. configurable: true
  51180. });
  51181. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51182. /**
  51183. * Gets the current frame of the first RuntimeAnimation
  51184. * Used to synchronize Animatables
  51185. */
  51186. get: function () {
  51187. if (this._runtimeAnimations.length === 0) {
  51188. return 0;
  51189. }
  51190. return this._runtimeAnimations[0].currentFrame;
  51191. },
  51192. enumerable: true,
  51193. configurable: true
  51194. });
  51195. Object.defineProperty(Animatable.prototype, "weight", {
  51196. /**
  51197. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51198. */
  51199. get: function () {
  51200. return this._weight;
  51201. },
  51202. set: function (value) {
  51203. if (value === -1) { // -1 is ok and means no weight
  51204. this._weight = -1;
  51205. return;
  51206. }
  51207. // Else weight must be in [0, 1] range
  51208. this._weight = Math.min(Math.max(value, 0), 1.0);
  51209. },
  51210. enumerable: true,
  51211. configurable: true
  51212. });
  51213. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51214. /**
  51215. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51216. */
  51217. get: function () {
  51218. return this._speedRatio;
  51219. },
  51220. set: function (value) {
  51221. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51222. var animation = this._runtimeAnimations[index];
  51223. animation._prepareForSpeedRatioChange(value);
  51224. }
  51225. this._speedRatio = value;
  51226. },
  51227. enumerable: true,
  51228. configurable: true
  51229. });
  51230. // Methods
  51231. /**
  51232. * Synchronize and normalize current Animatable with a source Animatable
  51233. * This is useful when using animation weights and when animations are not of the same length
  51234. * @param root defines the root Animatable to synchronize with
  51235. * @returns the current Animatable
  51236. */
  51237. Animatable.prototype.syncWith = function (root) {
  51238. this._syncRoot = root;
  51239. if (root) {
  51240. // Make sure this animatable will animate after the root
  51241. var index = this._scene._activeAnimatables.indexOf(this);
  51242. if (index > -1) {
  51243. this._scene._activeAnimatables.splice(index, 1);
  51244. this._scene._activeAnimatables.push(this);
  51245. }
  51246. }
  51247. return this;
  51248. };
  51249. /**
  51250. * Gets the list of runtime animations
  51251. * @returns an array of RuntimeAnimation
  51252. */
  51253. Animatable.prototype.getAnimations = function () {
  51254. return this._runtimeAnimations;
  51255. };
  51256. /**
  51257. * Adds more animations to the current animatable
  51258. * @param target defines the target of the animations
  51259. * @param animations defines the new animations to add
  51260. */
  51261. Animatable.prototype.appendAnimations = function (target, animations) {
  51262. for (var index = 0; index < animations.length; index++) {
  51263. var animation = animations[index];
  51264. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51265. }
  51266. };
  51267. /**
  51268. * Gets the source animation for a specific property
  51269. * @param property defines the propertyu to look for
  51270. * @returns null or the source animation for the given property
  51271. */
  51272. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51273. var runtimeAnimations = this._runtimeAnimations;
  51274. for (var index = 0; index < runtimeAnimations.length; index++) {
  51275. if (runtimeAnimations[index].animation.targetProperty === property) {
  51276. return runtimeAnimations[index].animation;
  51277. }
  51278. }
  51279. return null;
  51280. };
  51281. /**
  51282. * Gets the runtime animation for a specific property
  51283. * @param property defines the propertyu to look for
  51284. * @returns null or the runtime animation for the given property
  51285. */
  51286. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51287. var runtimeAnimations = this._runtimeAnimations;
  51288. for (var index = 0; index < runtimeAnimations.length; index++) {
  51289. if (runtimeAnimations[index].animation.targetProperty === property) {
  51290. return runtimeAnimations[index];
  51291. }
  51292. }
  51293. return null;
  51294. };
  51295. /**
  51296. * Resets the animatable to its original state
  51297. */
  51298. Animatable.prototype.reset = function () {
  51299. var runtimeAnimations = this._runtimeAnimations;
  51300. for (var index = 0; index < runtimeAnimations.length; index++) {
  51301. runtimeAnimations[index].reset(true);
  51302. }
  51303. this._localDelayOffset = null;
  51304. this._pausedDelay = null;
  51305. };
  51306. /**
  51307. * Allows the animatable to blend with current running animations
  51308. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51309. * @param blendingSpeed defines the blending speed to use
  51310. */
  51311. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51312. var runtimeAnimations = this._runtimeAnimations;
  51313. for (var index = 0; index < runtimeAnimations.length; index++) {
  51314. runtimeAnimations[index].animation.enableBlending = true;
  51315. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51316. }
  51317. };
  51318. /**
  51319. * Disable animation blending
  51320. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51321. */
  51322. Animatable.prototype.disableBlending = function () {
  51323. var runtimeAnimations = this._runtimeAnimations;
  51324. for (var index = 0; index < runtimeAnimations.length; index++) {
  51325. runtimeAnimations[index].animation.enableBlending = false;
  51326. }
  51327. };
  51328. /**
  51329. * Jump directly to a given frame
  51330. * @param frame defines the frame to jump to
  51331. */
  51332. Animatable.prototype.goToFrame = function (frame) {
  51333. var runtimeAnimations = this._runtimeAnimations;
  51334. if (runtimeAnimations[0]) {
  51335. var fps = runtimeAnimations[0].animation.framePerSecond;
  51336. var currentFrame = runtimeAnimations[0].currentFrame;
  51337. var adjustTime = frame - currentFrame;
  51338. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51339. if (this._localDelayOffset === null) {
  51340. this._localDelayOffset = 0;
  51341. }
  51342. this._localDelayOffset -= delay;
  51343. }
  51344. for (var index = 0; index < runtimeAnimations.length; index++) {
  51345. runtimeAnimations[index].goToFrame(frame);
  51346. }
  51347. };
  51348. /**
  51349. * Pause the animation
  51350. */
  51351. Animatable.prototype.pause = function () {
  51352. if (this._paused) {
  51353. return;
  51354. }
  51355. this._paused = true;
  51356. };
  51357. /**
  51358. * Restart the animation
  51359. */
  51360. Animatable.prototype.restart = function () {
  51361. this._paused = false;
  51362. };
  51363. Animatable.prototype._raiseOnAnimationEnd = function () {
  51364. if (this.onAnimationEnd) {
  51365. this.onAnimationEnd();
  51366. }
  51367. this.onAnimationEndObservable.notifyObservers(this);
  51368. };
  51369. /**
  51370. * Stop and delete the current animation
  51371. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51372. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51373. */
  51374. Animatable.prototype.stop = function (animationName, targetMask) {
  51375. if (animationName || targetMask) {
  51376. var idx = this._scene._activeAnimatables.indexOf(this);
  51377. if (idx > -1) {
  51378. var runtimeAnimations = this._runtimeAnimations;
  51379. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51380. var runtimeAnimation = runtimeAnimations[index];
  51381. if (animationName && runtimeAnimation.animation.name != animationName) {
  51382. continue;
  51383. }
  51384. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51385. continue;
  51386. }
  51387. runtimeAnimation.dispose();
  51388. runtimeAnimations.splice(index, 1);
  51389. }
  51390. if (runtimeAnimations.length == 0) {
  51391. this._scene._activeAnimatables.splice(idx, 1);
  51392. this._raiseOnAnimationEnd();
  51393. }
  51394. }
  51395. }
  51396. else {
  51397. var index = this._scene._activeAnimatables.indexOf(this);
  51398. if (index > -1) {
  51399. this._scene._activeAnimatables.splice(index, 1);
  51400. var runtimeAnimations = this._runtimeAnimations;
  51401. for (var index = 0; index < runtimeAnimations.length; index++) {
  51402. runtimeAnimations[index].dispose();
  51403. }
  51404. this._raiseOnAnimationEnd();
  51405. }
  51406. }
  51407. };
  51408. /**
  51409. * Wait asynchronously for the animation to end
  51410. * @returns a promise which will be fullfilled when the animation ends
  51411. */
  51412. Animatable.prototype.waitAsync = function () {
  51413. var _this = this;
  51414. return new Promise(function (resolve, reject) {
  51415. _this.onAnimationEndObservable.add(function () {
  51416. resolve(_this);
  51417. }, undefined, undefined, _this, true);
  51418. });
  51419. };
  51420. /** @hidden */
  51421. Animatable.prototype._animate = function (delay) {
  51422. if (this._paused) {
  51423. this.animationStarted = false;
  51424. if (this._pausedDelay === null) {
  51425. this._pausedDelay = delay;
  51426. }
  51427. return true;
  51428. }
  51429. if (this._localDelayOffset === null) {
  51430. this._localDelayOffset = delay;
  51431. this._pausedDelay = null;
  51432. }
  51433. else if (this._pausedDelay !== null) {
  51434. this._localDelayOffset += delay - this._pausedDelay;
  51435. this._pausedDelay = null;
  51436. }
  51437. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51438. return true;
  51439. }
  51440. // Animating
  51441. var running = false;
  51442. var runtimeAnimations = this._runtimeAnimations;
  51443. var index;
  51444. for (index = 0; index < runtimeAnimations.length; index++) {
  51445. var animation = runtimeAnimations[index];
  51446. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51447. running = running || isRunning;
  51448. }
  51449. this.animationStarted = running;
  51450. if (!running) {
  51451. if (this.disposeOnEnd) {
  51452. // Remove from active animatables
  51453. index = this._scene._activeAnimatables.indexOf(this);
  51454. this._scene._activeAnimatables.splice(index, 1);
  51455. // Dispose all runtime animations
  51456. for (index = 0; index < runtimeAnimations.length; index++) {
  51457. runtimeAnimations[index].dispose();
  51458. }
  51459. }
  51460. this._raiseOnAnimationEnd();
  51461. if (this.disposeOnEnd) {
  51462. this.onAnimationEnd = null;
  51463. this.onAnimationEndObservable.clear();
  51464. }
  51465. }
  51466. return running;
  51467. };
  51468. return Animatable;
  51469. }());
  51470. BABYLON.Animatable = Animatable;
  51471. })(BABYLON || (BABYLON = {}));
  51472. //# sourceMappingURL=babylon.animatable.js.map
  51473. var BABYLON;
  51474. (function (BABYLON) {
  51475. var EasingFunction = /** @class */ (function () {
  51476. function EasingFunction() {
  51477. // Properties
  51478. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51479. }
  51480. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51481. get: function () {
  51482. return EasingFunction._EASINGMODE_EASEIN;
  51483. },
  51484. enumerable: true,
  51485. configurable: true
  51486. });
  51487. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51488. get: function () {
  51489. return EasingFunction._EASINGMODE_EASEOUT;
  51490. },
  51491. enumerable: true,
  51492. configurable: true
  51493. });
  51494. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51495. get: function () {
  51496. return EasingFunction._EASINGMODE_EASEINOUT;
  51497. },
  51498. enumerable: true,
  51499. configurable: true
  51500. });
  51501. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51502. var n = Math.min(Math.max(easingMode, 0), 2);
  51503. this._easingMode = n;
  51504. };
  51505. EasingFunction.prototype.getEasingMode = function () {
  51506. return this._easingMode;
  51507. };
  51508. EasingFunction.prototype.easeInCore = function (gradient) {
  51509. throw new Error('You must implement this method');
  51510. };
  51511. EasingFunction.prototype.ease = function (gradient) {
  51512. switch (this._easingMode) {
  51513. case EasingFunction.EASINGMODE_EASEIN:
  51514. return this.easeInCore(gradient);
  51515. case EasingFunction.EASINGMODE_EASEOUT:
  51516. return (1 - this.easeInCore(1 - gradient));
  51517. }
  51518. if (gradient >= 0.5) {
  51519. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51520. }
  51521. return (this.easeInCore(gradient * 2) * 0.5);
  51522. };
  51523. //Statics
  51524. EasingFunction._EASINGMODE_EASEIN = 0;
  51525. EasingFunction._EASINGMODE_EASEOUT = 1;
  51526. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51527. return EasingFunction;
  51528. }());
  51529. BABYLON.EasingFunction = EasingFunction;
  51530. var CircleEase = /** @class */ (function (_super) {
  51531. __extends(CircleEase, _super);
  51532. function CircleEase() {
  51533. return _super !== null && _super.apply(this, arguments) || this;
  51534. }
  51535. CircleEase.prototype.easeInCore = function (gradient) {
  51536. gradient = Math.max(0, Math.min(1, gradient));
  51537. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51538. };
  51539. return CircleEase;
  51540. }(EasingFunction));
  51541. BABYLON.CircleEase = CircleEase;
  51542. var BackEase = /** @class */ (function (_super) {
  51543. __extends(BackEase, _super);
  51544. function BackEase(amplitude) {
  51545. if (amplitude === void 0) { amplitude = 1; }
  51546. var _this = _super.call(this) || this;
  51547. _this.amplitude = amplitude;
  51548. return _this;
  51549. }
  51550. BackEase.prototype.easeInCore = function (gradient) {
  51551. var num = Math.max(0, this.amplitude);
  51552. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51553. };
  51554. return BackEase;
  51555. }(EasingFunction));
  51556. BABYLON.BackEase = BackEase;
  51557. var BounceEase = /** @class */ (function (_super) {
  51558. __extends(BounceEase, _super);
  51559. function BounceEase(bounces, bounciness) {
  51560. if (bounces === void 0) { bounces = 3; }
  51561. if (bounciness === void 0) { bounciness = 2; }
  51562. var _this = _super.call(this) || this;
  51563. _this.bounces = bounces;
  51564. _this.bounciness = bounciness;
  51565. return _this;
  51566. }
  51567. BounceEase.prototype.easeInCore = function (gradient) {
  51568. var y = Math.max(0.0, this.bounces);
  51569. var bounciness = this.bounciness;
  51570. if (bounciness <= 1.0) {
  51571. bounciness = 1.001;
  51572. }
  51573. var num9 = Math.pow(bounciness, y);
  51574. var num5 = 1.0 - bounciness;
  51575. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51576. var num15 = gradient * num4;
  51577. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51578. var num3 = Math.floor(num65);
  51579. var num13 = num3 + 1.0;
  51580. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51581. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51582. var num7 = (num8 + num12) * 0.5;
  51583. var num6 = gradient - num7;
  51584. var num2 = num7 - num8;
  51585. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51586. };
  51587. return BounceEase;
  51588. }(EasingFunction));
  51589. BABYLON.BounceEase = BounceEase;
  51590. var CubicEase = /** @class */ (function (_super) {
  51591. __extends(CubicEase, _super);
  51592. function CubicEase() {
  51593. return _super !== null && _super.apply(this, arguments) || this;
  51594. }
  51595. CubicEase.prototype.easeInCore = function (gradient) {
  51596. return (gradient * gradient * gradient);
  51597. };
  51598. return CubicEase;
  51599. }(EasingFunction));
  51600. BABYLON.CubicEase = CubicEase;
  51601. var ElasticEase = /** @class */ (function (_super) {
  51602. __extends(ElasticEase, _super);
  51603. function ElasticEase(oscillations, springiness) {
  51604. if (oscillations === void 0) { oscillations = 3; }
  51605. if (springiness === void 0) { springiness = 3; }
  51606. var _this = _super.call(this) || this;
  51607. _this.oscillations = oscillations;
  51608. _this.springiness = springiness;
  51609. return _this;
  51610. }
  51611. ElasticEase.prototype.easeInCore = function (gradient) {
  51612. var num2;
  51613. var num3 = Math.max(0.0, this.oscillations);
  51614. var num = Math.max(0.0, this.springiness);
  51615. if (num == 0) {
  51616. num2 = gradient;
  51617. }
  51618. else {
  51619. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51620. }
  51621. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51622. };
  51623. return ElasticEase;
  51624. }(EasingFunction));
  51625. BABYLON.ElasticEase = ElasticEase;
  51626. var ExponentialEase = /** @class */ (function (_super) {
  51627. __extends(ExponentialEase, _super);
  51628. function ExponentialEase(exponent) {
  51629. if (exponent === void 0) { exponent = 2; }
  51630. var _this = _super.call(this) || this;
  51631. _this.exponent = exponent;
  51632. return _this;
  51633. }
  51634. ExponentialEase.prototype.easeInCore = function (gradient) {
  51635. if (this.exponent <= 0) {
  51636. return gradient;
  51637. }
  51638. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51639. };
  51640. return ExponentialEase;
  51641. }(EasingFunction));
  51642. BABYLON.ExponentialEase = ExponentialEase;
  51643. var PowerEase = /** @class */ (function (_super) {
  51644. __extends(PowerEase, _super);
  51645. function PowerEase(power) {
  51646. if (power === void 0) { power = 2; }
  51647. var _this = _super.call(this) || this;
  51648. _this.power = power;
  51649. return _this;
  51650. }
  51651. PowerEase.prototype.easeInCore = function (gradient) {
  51652. var y = Math.max(0.0, this.power);
  51653. return Math.pow(gradient, y);
  51654. };
  51655. return PowerEase;
  51656. }(EasingFunction));
  51657. BABYLON.PowerEase = PowerEase;
  51658. var QuadraticEase = /** @class */ (function (_super) {
  51659. __extends(QuadraticEase, _super);
  51660. function QuadraticEase() {
  51661. return _super !== null && _super.apply(this, arguments) || this;
  51662. }
  51663. QuadraticEase.prototype.easeInCore = function (gradient) {
  51664. return (gradient * gradient);
  51665. };
  51666. return QuadraticEase;
  51667. }(EasingFunction));
  51668. BABYLON.QuadraticEase = QuadraticEase;
  51669. var QuarticEase = /** @class */ (function (_super) {
  51670. __extends(QuarticEase, _super);
  51671. function QuarticEase() {
  51672. return _super !== null && _super.apply(this, arguments) || this;
  51673. }
  51674. QuarticEase.prototype.easeInCore = function (gradient) {
  51675. return (gradient * gradient * gradient * gradient);
  51676. };
  51677. return QuarticEase;
  51678. }(EasingFunction));
  51679. BABYLON.QuarticEase = QuarticEase;
  51680. var QuinticEase = /** @class */ (function (_super) {
  51681. __extends(QuinticEase, _super);
  51682. function QuinticEase() {
  51683. return _super !== null && _super.apply(this, arguments) || this;
  51684. }
  51685. QuinticEase.prototype.easeInCore = function (gradient) {
  51686. return (gradient * gradient * gradient * gradient * gradient);
  51687. };
  51688. return QuinticEase;
  51689. }(EasingFunction));
  51690. BABYLON.QuinticEase = QuinticEase;
  51691. var SineEase = /** @class */ (function (_super) {
  51692. __extends(SineEase, _super);
  51693. function SineEase() {
  51694. return _super !== null && _super.apply(this, arguments) || this;
  51695. }
  51696. SineEase.prototype.easeInCore = function (gradient) {
  51697. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51698. };
  51699. return SineEase;
  51700. }(EasingFunction));
  51701. BABYLON.SineEase = SineEase;
  51702. var BezierCurveEase = /** @class */ (function (_super) {
  51703. __extends(BezierCurveEase, _super);
  51704. function BezierCurveEase(x1, y1, x2, y2) {
  51705. if (x1 === void 0) { x1 = 0; }
  51706. if (y1 === void 0) { y1 = 0; }
  51707. if (x2 === void 0) { x2 = 1; }
  51708. if (y2 === void 0) { y2 = 1; }
  51709. var _this = _super.call(this) || this;
  51710. _this.x1 = x1;
  51711. _this.y1 = y1;
  51712. _this.x2 = x2;
  51713. _this.y2 = y2;
  51714. return _this;
  51715. }
  51716. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51717. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51718. };
  51719. return BezierCurveEase;
  51720. }(EasingFunction));
  51721. BABYLON.BezierCurveEase = BezierCurveEase;
  51722. })(BABYLON || (BABYLON = {}));
  51723. //# sourceMappingURL=babylon.easing.js.map
  51724. var BABYLON;
  51725. (function (BABYLON) {
  51726. /**
  51727. * A Condition applied to an Action
  51728. */
  51729. var Condition = /** @class */ (function () {
  51730. /**
  51731. * Creates a new Condition
  51732. * @param actionManager the manager of the action the condition is applied to
  51733. */
  51734. function Condition(actionManager) {
  51735. this._actionManager = actionManager;
  51736. }
  51737. /**
  51738. * Check if the current condition is valid
  51739. * @returns a boolean
  51740. */
  51741. Condition.prototype.isValid = function () {
  51742. return true;
  51743. };
  51744. /**
  51745. * Internal only
  51746. * @hidden
  51747. */
  51748. Condition.prototype._getProperty = function (propertyPath) {
  51749. return this._actionManager._getProperty(propertyPath);
  51750. };
  51751. /**
  51752. * Internal only
  51753. * @hidden
  51754. */
  51755. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51756. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51757. };
  51758. /**
  51759. * Serialize placeholder for child classes
  51760. * @returns the serialized object
  51761. */
  51762. Condition.prototype.serialize = function () {
  51763. };
  51764. /**
  51765. * Internal only
  51766. * @hidden
  51767. */
  51768. Condition.prototype._serialize = function (serializedCondition) {
  51769. return {
  51770. type: 2,
  51771. children: [],
  51772. name: serializedCondition.name,
  51773. properties: serializedCondition.properties
  51774. };
  51775. };
  51776. return Condition;
  51777. }());
  51778. BABYLON.Condition = Condition;
  51779. /**
  51780. * Defines specific conditional operators as extensions of Condition
  51781. */
  51782. var ValueCondition = /** @class */ (function (_super) {
  51783. __extends(ValueCondition, _super);
  51784. /**
  51785. * Creates a new ValueCondition
  51786. * @param actionManager manager for the action the condition applies to
  51787. * @param target for the action
  51788. * @param propertyPath path to specify the property of the target the conditional operator uses
  51789. * @param value the value compared by the conditional operator against the current value of the property
  51790. * @param operator the conditional operator, default ValueCondition.IsEqual
  51791. */
  51792. function ValueCondition(actionManager, target,
  51793. /** path to specify the property of the target the conditional operator uses */
  51794. propertyPath,
  51795. /** the value compared by the conditional operator against the current value of the property */
  51796. value,
  51797. /** the conditional operator, default ValueCondition.IsEqual */
  51798. operator) {
  51799. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51800. var _this = _super.call(this, actionManager) || this;
  51801. _this.propertyPath = propertyPath;
  51802. _this.value = value;
  51803. _this.operator = operator;
  51804. _this._target = target;
  51805. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51806. _this._property = _this._getProperty(_this.propertyPath);
  51807. return _this;
  51808. }
  51809. Object.defineProperty(ValueCondition, "IsEqual", {
  51810. /**
  51811. * returns the number for IsEqual
  51812. */
  51813. get: function () {
  51814. return ValueCondition._IsEqual;
  51815. },
  51816. enumerable: true,
  51817. configurable: true
  51818. });
  51819. Object.defineProperty(ValueCondition, "IsDifferent", {
  51820. /**
  51821. * Returns the number for IsDifferent
  51822. */
  51823. get: function () {
  51824. return ValueCondition._IsDifferent;
  51825. },
  51826. enumerable: true,
  51827. configurable: true
  51828. });
  51829. Object.defineProperty(ValueCondition, "IsGreater", {
  51830. /**
  51831. * Returns the number for IsGreater
  51832. */
  51833. get: function () {
  51834. return ValueCondition._IsGreater;
  51835. },
  51836. enumerable: true,
  51837. configurable: true
  51838. });
  51839. Object.defineProperty(ValueCondition, "IsLesser", {
  51840. /**
  51841. * Returns the number for IsLesser
  51842. */
  51843. get: function () {
  51844. return ValueCondition._IsLesser;
  51845. },
  51846. enumerable: true,
  51847. configurable: true
  51848. });
  51849. /**
  51850. * Compares the given value with the property value for the specified conditional operator
  51851. * @returns the result of the comparison
  51852. */
  51853. ValueCondition.prototype.isValid = function () {
  51854. switch (this.operator) {
  51855. case ValueCondition.IsGreater:
  51856. return this._effectiveTarget[this._property] > this.value;
  51857. case ValueCondition.IsLesser:
  51858. return this._effectiveTarget[this._property] < this.value;
  51859. case ValueCondition.IsEqual:
  51860. case ValueCondition.IsDifferent:
  51861. var check;
  51862. if (this.value.equals) {
  51863. check = this.value.equals(this._effectiveTarget[this._property]);
  51864. }
  51865. else {
  51866. check = this.value === this._effectiveTarget[this._property];
  51867. }
  51868. return this.operator === ValueCondition.IsEqual ? check : !check;
  51869. }
  51870. return false;
  51871. };
  51872. /**
  51873. * Serialize the ValueCondition into a JSON compatible object
  51874. * @returns serialization object
  51875. */
  51876. ValueCondition.prototype.serialize = function () {
  51877. return this._serialize({
  51878. name: "ValueCondition",
  51879. properties: [
  51880. BABYLON.Action._GetTargetProperty(this._target),
  51881. { name: "propertyPath", value: this.propertyPath },
  51882. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51883. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51884. ]
  51885. });
  51886. };
  51887. /**
  51888. * Gets the name of the conditional operator for the ValueCondition
  51889. * @param operator the conditional operator
  51890. * @returns the name
  51891. */
  51892. ValueCondition.GetOperatorName = function (operator) {
  51893. switch (operator) {
  51894. case ValueCondition._IsEqual: return "IsEqual";
  51895. case ValueCondition._IsDifferent: return "IsDifferent";
  51896. case ValueCondition._IsGreater: return "IsGreater";
  51897. case ValueCondition._IsLesser: return "IsLesser";
  51898. default: return "";
  51899. }
  51900. };
  51901. /**
  51902. * Internal only
  51903. * @hidden
  51904. */
  51905. ValueCondition._IsEqual = 0;
  51906. /**
  51907. * Internal only
  51908. * @hidden
  51909. */
  51910. ValueCondition._IsDifferent = 1;
  51911. /**
  51912. * Internal only
  51913. * @hidden
  51914. */
  51915. ValueCondition._IsGreater = 2;
  51916. /**
  51917. * Internal only
  51918. * @hidden
  51919. */
  51920. ValueCondition._IsLesser = 3;
  51921. return ValueCondition;
  51922. }(Condition));
  51923. BABYLON.ValueCondition = ValueCondition;
  51924. /**
  51925. * Defines a predicate condition as an extension of Condition
  51926. */
  51927. var PredicateCondition = /** @class */ (function (_super) {
  51928. __extends(PredicateCondition, _super);
  51929. /**
  51930. * Creates a new PredicateCondition
  51931. * @param actionManager manager for the action the condition applies to
  51932. * @param predicate defines the predicate function used to validate the condition
  51933. */
  51934. function PredicateCondition(actionManager,
  51935. /** defines the predicate function used to validate the condition */
  51936. predicate) {
  51937. var _this = _super.call(this, actionManager) || this;
  51938. _this.predicate = predicate;
  51939. return _this;
  51940. }
  51941. /**
  51942. * @returns the validity of the predicate condition
  51943. */
  51944. PredicateCondition.prototype.isValid = function () {
  51945. return this.predicate();
  51946. };
  51947. return PredicateCondition;
  51948. }(Condition));
  51949. BABYLON.PredicateCondition = PredicateCondition;
  51950. /**
  51951. * Defines a state condition as an extension of Condition
  51952. */
  51953. var StateCondition = /** @class */ (function (_super) {
  51954. __extends(StateCondition, _super);
  51955. /**
  51956. * Creates a new StateCondition
  51957. * @param actionManager manager for the action the condition applies to
  51958. * @param target of the condition
  51959. * @param value to compare with target state
  51960. */
  51961. function StateCondition(actionManager, target, value) {
  51962. var _this = _super.call(this, actionManager) || this;
  51963. _this.value = value;
  51964. _this._target = target;
  51965. return _this;
  51966. }
  51967. /**
  51968. * @returns the validity of the state
  51969. */
  51970. StateCondition.prototype.isValid = function () {
  51971. return this._target.state === this.value;
  51972. };
  51973. /**
  51974. * Serialize the StateCondition into a JSON compatible object
  51975. * @returns serialization object
  51976. */
  51977. StateCondition.prototype.serialize = function () {
  51978. return this._serialize({
  51979. name: "StateCondition",
  51980. properties: [
  51981. BABYLON.Action._GetTargetProperty(this._target),
  51982. { name: "value", value: this.value }
  51983. ]
  51984. });
  51985. };
  51986. return StateCondition;
  51987. }(Condition));
  51988. BABYLON.StateCondition = StateCondition;
  51989. })(BABYLON || (BABYLON = {}));
  51990. //# sourceMappingURL=babylon.condition.js.map
  51991. var BABYLON;
  51992. (function (BABYLON) {
  51993. /**
  51994. * The action to be carried out following a trigger
  51995. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51996. */
  51997. var Action = /** @class */ (function () {
  51998. /**
  51999. * Creates a new Action
  52000. * @param triggerOptions the trigger, with or without parameters, for the action
  52001. * @param condition an optional determinant of action
  52002. */
  52003. function Action(
  52004. /** the trigger, with or without parameters, for the action */
  52005. triggerOptions, condition) {
  52006. this.triggerOptions = triggerOptions;
  52007. /**
  52008. * An event triggered prior to action being executed.
  52009. */
  52010. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52011. if (triggerOptions.parameter) {
  52012. this.trigger = triggerOptions.trigger;
  52013. this._triggerParameter = triggerOptions.parameter;
  52014. }
  52015. else {
  52016. this.trigger = triggerOptions;
  52017. }
  52018. this._nextActiveAction = this;
  52019. this._condition = condition;
  52020. }
  52021. /**
  52022. * Internal only
  52023. * @hidden
  52024. */
  52025. Action.prototype._prepare = function () {
  52026. };
  52027. /**
  52028. * Gets the trigger parameters
  52029. * @returns the trigger parameters
  52030. */
  52031. Action.prototype.getTriggerParameter = function () {
  52032. return this._triggerParameter;
  52033. };
  52034. /**
  52035. * Internal only - executes current action event
  52036. * @hidden
  52037. */
  52038. Action.prototype._executeCurrent = function (evt) {
  52039. if (this._nextActiveAction._condition) {
  52040. var condition = this._nextActiveAction._condition;
  52041. var currentRenderId = this._actionManager.getScene().getRenderId();
  52042. // We cache the current evaluation for the current frame
  52043. if (condition._evaluationId === currentRenderId) {
  52044. if (!condition._currentResult) {
  52045. return;
  52046. }
  52047. }
  52048. else {
  52049. condition._evaluationId = currentRenderId;
  52050. if (!condition.isValid()) {
  52051. condition._currentResult = false;
  52052. return;
  52053. }
  52054. condition._currentResult = true;
  52055. }
  52056. }
  52057. this.onBeforeExecuteObservable.notifyObservers(this);
  52058. this._nextActiveAction.execute(evt);
  52059. this.skipToNextActiveAction();
  52060. };
  52061. /**
  52062. * Execute placeholder for child classes
  52063. * @param evt optional action event
  52064. */
  52065. Action.prototype.execute = function (evt) {
  52066. };
  52067. /**
  52068. * Skips to next active action
  52069. */
  52070. Action.prototype.skipToNextActiveAction = function () {
  52071. if (this._nextActiveAction._child) {
  52072. if (!this._nextActiveAction._child._actionManager) {
  52073. this._nextActiveAction._child._actionManager = this._actionManager;
  52074. }
  52075. this._nextActiveAction = this._nextActiveAction._child;
  52076. }
  52077. else {
  52078. this._nextActiveAction = this;
  52079. }
  52080. };
  52081. /**
  52082. * Adds action to chain of actions, may be a DoNothingAction
  52083. * @param action defines the next action to execute
  52084. * @returns The action passed in
  52085. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52086. */
  52087. Action.prototype.then = function (action) {
  52088. this._child = action;
  52089. action._actionManager = this._actionManager;
  52090. action._prepare();
  52091. return action;
  52092. };
  52093. /**
  52094. * Internal only
  52095. * @hidden
  52096. */
  52097. Action.prototype._getProperty = function (propertyPath) {
  52098. return this._actionManager._getProperty(propertyPath);
  52099. };
  52100. /**
  52101. * Internal only
  52102. * @hidden
  52103. */
  52104. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52105. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52106. };
  52107. /**
  52108. * Serialize placeholder for child classes
  52109. * @param parent of child
  52110. * @returns the serialized object
  52111. */
  52112. Action.prototype.serialize = function (parent) {
  52113. };
  52114. /**
  52115. * Internal only called by serialize
  52116. * @hidden
  52117. */
  52118. Action.prototype._serialize = function (serializedAction, parent) {
  52119. var serializationObject = {
  52120. type: 1,
  52121. children: [],
  52122. name: serializedAction.name,
  52123. properties: serializedAction.properties || []
  52124. };
  52125. // Serialize child
  52126. if (this._child) {
  52127. this._child.serialize(serializationObject);
  52128. }
  52129. // Check if "this" has a condition
  52130. if (this._condition) {
  52131. var serializedCondition = this._condition.serialize();
  52132. serializedCondition.children.push(serializationObject);
  52133. if (parent) {
  52134. parent.children.push(serializedCondition);
  52135. }
  52136. return serializedCondition;
  52137. }
  52138. if (parent) {
  52139. parent.children.push(serializationObject);
  52140. }
  52141. return serializationObject;
  52142. };
  52143. /**
  52144. * Internal only
  52145. * @hidden
  52146. */
  52147. Action._SerializeValueAsString = function (value) {
  52148. if (typeof value === "number") {
  52149. return value.toString();
  52150. }
  52151. if (typeof value === "boolean") {
  52152. return value ? "true" : "false";
  52153. }
  52154. if (value instanceof BABYLON.Vector2) {
  52155. return value.x + ", " + value.y;
  52156. }
  52157. if (value instanceof BABYLON.Vector3) {
  52158. return value.x + ", " + value.y + ", " + value.z;
  52159. }
  52160. if (value instanceof BABYLON.Color3) {
  52161. return value.r + ", " + value.g + ", " + value.b;
  52162. }
  52163. if (value instanceof BABYLON.Color4) {
  52164. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52165. }
  52166. return value; // string
  52167. };
  52168. /**
  52169. * Internal only
  52170. * @hidden
  52171. */
  52172. Action._GetTargetProperty = function (target) {
  52173. return {
  52174. name: "target",
  52175. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52176. : target instanceof BABYLON.Light ? "LightProperties"
  52177. : target instanceof BABYLON.Camera ? "CameraProperties"
  52178. : "SceneProperties",
  52179. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52180. };
  52181. };
  52182. return Action;
  52183. }());
  52184. BABYLON.Action = Action;
  52185. })(BABYLON || (BABYLON = {}));
  52186. //# sourceMappingURL=babylon.action.js.map
  52187. var BABYLON;
  52188. (function (BABYLON) {
  52189. /**
  52190. * ActionEvent is the event being sent when an action is triggered.
  52191. */
  52192. var ActionEvent = /** @class */ (function () {
  52193. /**
  52194. * Creates a new ActionEvent
  52195. * @param source The mesh or sprite that triggered the action
  52196. * @param pointerX The X mouse cursor position at the time of the event
  52197. * @param pointerY The Y mouse cursor position at the time of the event
  52198. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52199. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52200. * @param additionalData additional data for the event
  52201. */
  52202. function ActionEvent(
  52203. /** The mesh or sprite that triggered the action */
  52204. source,
  52205. /** The X mouse cursor position at the time of the event */
  52206. pointerX,
  52207. /** The Y mouse cursor position at the time of the event */
  52208. pointerY,
  52209. /** The mesh that is currently pointed at (can be null) */
  52210. meshUnderPointer,
  52211. /** the original (browser) event that triggered the ActionEvent */
  52212. sourceEvent,
  52213. /** additional data for the event */
  52214. additionalData) {
  52215. this.source = source;
  52216. this.pointerX = pointerX;
  52217. this.pointerY = pointerY;
  52218. this.meshUnderPointer = meshUnderPointer;
  52219. this.sourceEvent = sourceEvent;
  52220. this.additionalData = additionalData;
  52221. }
  52222. /**
  52223. * Helper function to auto-create an ActionEvent from a source mesh.
  52224. * @param source The source mesh that triggered the event
  52225. * @param evt The original (browser) event
  52226. * @param additionalData additional data for the event
  52227. * @returns the new ActionEvent
  52228. */
  52229. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52230. var scene = source.getScene();
  52231. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52232. };
  52233. /**
  52234. * Helper function to auto-create an ActionEvent from a source sprite
  52235. * @param source The source sprite that triggered the event
  52236. * @param scene Scene associated with the sprite
  52237. * @param evt The original (browser) event
  52238. * @param additionalData additional data for the event
  52239. * @returns the new ActionEvent
  52240. */
  52241. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52242. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52243. };
  52244. /**
  52245. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52246. * @param scene the scene where the event occurred
  52247. * @param evt The original (browser) event
  52248. * @returns the new ActionEvent
  52249. */
  52250. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52251. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52252. };
  52253. /**
  52254. * Helper function to auto-create an ActionEvent from a primitive
  52255. * @param prim defines the target primitive
  52256. * @param pointerPos defines the pointer position
  52257. * @param evt The original (browser) event
  52258. * @param additionalData additional data for the event
  52259. * @returns the new ActionEvent
  52260. */
  52261. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52262. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52263. };
  52264. return ActionEvent;
  52265. }());
  52266. BABYLON.ActionEvent = ActionEvent;
  52267. /**
  52268. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52269. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52270. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52271. */
  52272. var ActionManager = /** @class */ (function () {
  52273. /**
  52274. * Creates a new action manager
  52275. * @param scene defines the hosting scene
  52276. */
  52277. function ActionManager(scene) {
  52278. // Members
  52279. /** Gets the list of actions */
  52280. this.actions = new Array();
  52281. /** Gets the cursor to use when hovering items */
  52282. this.hoverCursor = '';
  52283. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52284. scene.actionManagers.push(this);
  52285. }
  52286. Object.defineProperty(ActionManager, "NothingTrigger", {
  52287. /**
  52288. * Nothing
  52289. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52290. */
  52291. get: function () {
  52292. return ActionManager._NothingTrigger;
  52293. },
  52294. enumerable: true,
  52295. configurable: true
  52296. });
  52297. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52298. /**
  52299. * On pick
  52300. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52301. */
  52302. get: function () {
  52303. return ActionManager._OnPickTrigger;
  52304. },
  52305. enumerable: true,
  52306. configurable: true
  52307. });
  52308. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52309. /**
  52310. * On left pick
  52311. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52312. */
  52313. get: function () {
  52314. return ActionManager._OnLeftPickTrigger;
  52315. },
  52316. enumerable: true,
  52317. configurable: true
  52318. });
  52319. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52320. /**
  52321. * On right pick
  52322. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52323. */
  52324. get: function () {
  52325. return ActionManager._OnRightPickTrigger;
  52326. },
  52327. enumerable: true,
  52328. configurable: true
  52329. });
  52330. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52331. /**
  52332. * On center pick
  52333. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52334. */
  52335. get: function () {
  52336. return ActionManager._OnCenterPickTrigger;
  52337. },
  52338. enumerable: true,
  52339. configurable: true
  52340. });
  52341. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52342. /**
  52343. * On pick down
  52344. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52345. */
  52346. get: function () {
  52347. return ActionManager._OnPickDownTrigger;
  52348. },
  52349. enumerable: true,
  52350. configurable: true
  52351. });
  52352. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52353. /**
  52354. * On double pick
  52355. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52356. */
  52357. get: function () {
  52358. return ActionManager._OnDoublePickTrigger;
  52359. },
  52360. enumerable: true,
  52361. configurable: true
  52362. });
  52363. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52364. /**
  52365. * On pick up
  52366. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52367. */
  52368. get: function () {
  52369. return ActionManager._OnPickUpTrigger;
  52370. },
  52371. enumerable: true,
  52372. configurable: true
  52373. });
  52374. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52375. /**
  52376. * On pick out.
  52377. * This trigger will only be raised if you also declared a OnPickDown
  52378. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52379. */
  52380. get: function () {
  52381. return ActionManager._OnPickOutTrigger;
  52382. },
  52383. enumerable: true,
  52384. configurable: true
  52385. });
  52386. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52387. /**
  52388. * On long press
  52389. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52390. */
  52391. get: function () {
  52392. return ActionManager._OnLongPressTrigger;
  52393. },
  52394. enumerable: true,
  52395. configurable: true
  52396. });
  52397. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52398. /**
  52399. * On pointer over
  52400. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52401. */
  52402. get: function () {
  52403. return ActionManager._OnPointerOverTrigger;
  52404. },
  52405. enumerable: true,
  52406. configurable: true
  52407. });
  52408. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52409. /**
  52410. * On pointer out
  52411. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52412. */
  52413. get: function () {
  52414. return ActionManager._OnPointerOutTrigger;
  52415. },
  52416. enumerable: true,
  52417. configurable: true
  52418. });
  52419. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52420. /**
  52421. * On every frame
  52422. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52423. */
  52424. get: function () {
  52425. return ActionManager._OnEveryFrameTrigger;
  52426. },
  52427. enumerable: true,
  52428. configurable: true
  52429. });
  52430. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52431. /**
  52432. * On intersection enter
  52433. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52434. */
  52435. get: function () {
  52436. return ActionManager._OnIntersectionEnterTrigger;
  52437. },
  52438. enumerable: true,
  52439. configurable: true
  52440. });
  52441. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52442. /**
  52443. * On intersection exit
  52444. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52445. */
  52446. get: function () {
  52447. return ActionManager._OnIntersectionExitTrigger;
  52448. },
  52449. enumerable: true,
  52450. configurable: true
  52451. });
  52452. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52453. /**
  52454. * On key down
  52455. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52456. */
  52457. get: function () {
  52458. return ActionManager._OnKeyDownTrigger;
  52459. },
  52460. enumerable: true,
  52461. configurable: true
  52462. });
  52463. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52464. /**
  52465. * On key up
  52466. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52467. */
  52468. get: function () {
  52469. return ActionManager._OnKeyUpTrigger;
  52470. },
  52471. enumerable: true,
  52472. configurable: true
  52473. });
  52474. // Methods
  52475. /**
  52476. * Releases all associated resources
  52477. */
  52478. ActionManager.prototype.dispose = function () {
  52479. var index = this._scene.actionManagers.indexOf(this);
  52480. for (var i = 0; i < this.actions.length; i++) {
  52481. var action = this.actions[i];
  52482. ActionManager.Triggers[action.trigger]--;
  52483. if (ActionManager.Triggers[action.trigger] === 0) {
  52484. delete ActionManager.Triggers[action.trigger];
  52485. }
  52486. }
  52487. if (index > -1) {
  52488. this._scene.actionManagers.splice(index, 1);
  52489. }
  52490. };
  52491. /**
  52492. * Gets hosting scene
  52493. * @returns the hosting scene
  52494. */
  52495. ActionManager.prototype.getScene = function () {
  52496. return this._scene;
  52497. };
  52498. /**
  52499. * Does this action manager handles actions of any of the given triggers
  52500. * @param triggers defines the triggers to be tested
  52501. * @return a boolean indicating whether one (or more) of the triggers is handled
  52502. */
  52503. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52504. for (var index = 0; index < this.actions.length; index++) {
  52505. var action = this.actions[index];
  52506. if (triggers.indexOf(action.trigger) > -1) {
  52507. return true;
  52508. }
  52509. }
  52510. return false;
  52511. };
  52512. /**
  52513. * Does this action manager handles actions of a given trigger
  52514. * @param trigger defines the trigger to be tested
  52515. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52516. * @return whether the trigger is handled
  52517. */
  52518. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52519. for (var index = 0; index < this.actions.length; index++) {
  52520. var action = this.actions[index];
  52521. if (action.trigger === trigger) {
  52522. if (parameterPredicate) {
  52523. if (parameterPredicate(action.getTriggerParameter())) {
  52524. return true;
  52525. }
  52526. }
  52527. else {
  52528. return true;
  52529. }
  52530. }
  52531. }
  52532. return false;
  52533. };
  52534. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52535. /**
  52536. * Does this action manager has pointer triggers
  52537. */
  52538. get: function () {
  52539. for (var index = 0; index < this.actions.length; index++) {
  52540. var action = this.actions[index];
  52541. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52542. return true;
  52543. }
  52544. }
  52545. return false;
  52546. },
  52547. enumerable: true,
  52548. configurable: true
  52549. });
  52550. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52551. /**
  52552. * Does this action manager has pick triggers
  52553. */
  52554. get: function () {
  52555. for (var index = 0; index < this.actions.length; index++) {
  52556. var action = this.actions[index];
  52557. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52558. return true;
  52559. }
  52560. }
  52561. return false;
  52562. },
  52563. enumerable: true,
  52564. configurable: true
  52565. });
  52566. Object.defineProperty(ActionManager, "HasTriggers", {
  52567. /**
  52568. * Does exist one action manager with at least one trigger
  52569. **/
  52570. get: function () {
  52571. for (var t in ActionManager.Triggers) {
  52572. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52573. return true;
  52574. }
  52575. }
  52576. return false;
  52577. },
  52578. enumerable: true,
  52579. configurable: true
  52580. });
  52581. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52582. /**
  52583. * Does exist one action manager with at least one pick trigger
  52584. **/
  52585. get: function () {
  52586. for (var t in ActionManager.Triggers) {
  52587. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52588. var t_int = parseInt(t);
  52589. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52590. return true;
  52591. }
  52592. }
  52593. }
  52594. return false;
  52595. },
  52596. enumerable: true,
  52597. configurable: true
  52598. });
  52599. /**
  52600. * Does exist one action manager that handles actions of a given trigger
  52601. * @param trigger defines the trigger to be tested
  52602. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52603. **/
  52604. ActionManager.HasSpecificTrigger = function (trigger) {
  52605. for (var t in ActionManager.Triggers) {
  52606. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52607. var t_int = parseInt(t);
  52608. if (t_int === trigger) {
  52609. return true;
  52610. }
  52611. }
  52612. }
  52613. return false;
  52614. };
  52615. /**
  52616. * Registers an action to this action manager
  52617. * @param action defines the action to be registered
  52618. * @return the action amended (prepared) after registration
  52619. */
  52620. ActionManager.prototype.registerAction = function (action) {
  52621. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52622. if (this.getScene().actionManager !== this) {
  52623. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52624. return null;
  52625. }
  52626. }
  52627. this.actions.push(action);
  52628. if (ActionManager.Triggers[action.trigger]) {
  52629. ActionManager.Triggers[action.trigger]++;
  52630. }
  52631. else {
  52632. ActionManager.Triggers[action.trigger] = 1;
  52633. }
  52634. action._actionManager = this;
  52635. action._prepare();
  52636. return action;
  52637. };
  52638. /**
  52639. * Unregisters an action to this action manager
  52640. * @param action defines the action to be unregistered
  52641. * @return a boolean indicating whether the action has been unregistered
  52642. */
  52643. ActionManager.prototype.unregisterAction = function (action) {
  52644. var index = this.actions.indexOf(action);
  52645. if (index !== -1) {
  52646. this.actions.splice(index, 1);
  52647. ActionManager.Triggers[action.trigger] -= 1;
  52648. if (ActionManager.Triggers[action.trigger] === 0) {
  52649. delete ActionManager.Triggers[action.trigger];
  52650. }
  52651. delete action._actionManager;
  52652. return true;
  52653. }
  52654. return false;
  52655. };
  52656. /**
  52657. * Process a specific trigger
  52658. * @param trigger defines the trigger to process
  52659. * @param evt defines the event details to be processed
  52660. */
  52661. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52662. for (var index = 0; index < this.actions.length; index++) {
  52663. var action = this.actions[index];
  52664. if (action.trigger === trigger) {
  52665. if (evt) {
  52666. if (trigger === ActionManager.OnKeyUpTrigger
  52667. || trigger === ActionManager.OnKeyDownTrigger) {
  52668. var parameter = action.getTriggerParameter();
  52669. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52670. if (!parameter.toLowerCase) {
  52671. continue;
  52672. }
  52673. var lowerCase = parameter.toLowerCase();
  52674. if (lowerCase !== evt.sourceEvent.key) {
  52675. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52676. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52677. if (actualkey !== lowerCase) {
  52678. continue;
  52679. }
  52680. }
  52681. }
  52682. }
  52683. }
  52684. action._executeCurrent(evt);
  52685. }
  52686. }
  52687. };
  52688. /** @hidden */
  52689. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52690. var properties = propertyPath.split(".");
  52691. for (var index = 0; index < properties.length - 1; index++) {
  52692. target = target[properties[index]];
  52693. }
  52694. return target;
  52695. };
  52696. /** @hidden */
  52697. ActionManager.prototype._getProperty = function (propertyPath) {
  52698. var properties = propertyPath.split(".");
  52699. return properties[properties.length - 1];
  52700. };
  52701. /**
  52702. * Serialize this manager to a JSON object
  52703. * @param name defines the property name to store this manager
  52704. * @returns a JSON representation of this manager
  52705. */
  52706. ActionManager.prototype.serialize = function (name) {
  52707. var root = {
  52708. children: new Array(),
  52709. name: name,
  52710. type: 3,
  52711. properties: new Array() // Empty for root but required
  52712. };
  52713. for (var i = 0; i < this.actions.length; i++) {
  52714. var triggerObject = {
  52715. type: 0,
  52716. children: new Array(),
  52717. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52718. properties: new Array()
  52719. };
  52720. var triggerOptions = this.actions[i].triggerOptions;
  52721. if (triggerOptions && typeof triggerOptions !== "number") {
  52722. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52723. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52724. }
  52725. else {
  52726. var parameter = {};
  52727. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52728. if (triggerOptions.parameter.mesh) {
  52729. parameter._meshId = triggerOptions.parameter.mesh.id;
  52730. }
  52731. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52732. }
  52733. }
  52734. // Serialize child action, recursively
  52735. this.actions[i].serialize(triggerObject);
  52736. // Add serialized trigger
  52737. root.children.push(triggerObject);
  52738. }
  52739. return root;
  52740. };
  52741. /**
  52742. * Creates a new ActionManager from a JSON data
  52743. * @param parsedActions defines the JSON data to read from
  52744. * @param object defines the hosting mesh
  52745. * @param scene defines the hosting scene
  52746. */
  52747. ActionManager.Parse = function (parsedActions, object, scene) {
  52748. var actionManager = new ActionManager(scene);
  52749. if (object === null)
  52750. scene.actionManager = actionManager;
  52751. else
  52752. object.actionManager = actionManager;
  52753. // instanciate a new object
  52754. var instanciate = function (name, params) {
  52755. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52756. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52757. newInstance.constructor.apply(newInstance, params);
  52758. return newInstance;
  52759. };
  52760. var parseParameter = function (name, value, target, propertyPath) {
  52761. if (propertyPath === null) {
  52762. // String, boolean or float
  52763. var floatValue = parseFloat(value);
  52764. if (value === "true" || value === "false")
  52765. return value === "true";
  52766. else
  52767. return isNaN(floatValue) ? value : floatValue;
  52768. }
  52769. var effectiveTarget = propertyPath.split(".");
  52770. var values = value.split(",");
  52771. // Get effective Target
  52772. for (var i = 0; i < effectiveTarget.length; i++) {
  52773. target = target[effectiveTarget[i]];
  52774. }
  52775. // Return appropriate value with its type
  52776. if (typeof (target) === "boolean")
  52777. return values[0] === "true";
  52778. if (typeof (target) === "string")
  52779. return values[0];
  52780. // Parameters with multiple values such as Vector3 etc.
  52781. var split = new Array();
  52782. for (var i = 0; i < values.length; i++)
  52783. split.push(parseFloat(values[i]));
  52784. if (target instanceof BABYLON.Vector3)
  52785. return BABYLON.Vector3.FromArray(split);
  52786. if (target instanceof BABYLON.Vector4)
  52787. return BABYLON.Vector4.FromArray(split);
  52788. if (target instanceof BABYLON.Color3)
  52789. return BABYLON.Color3.FromArray(split);
  52790. if (target instanceof BABYLON.Color4)
  52791. return BABYLON.Color4.FromArray(split);
  52792. return parseFloat(values[0]);
  52793. };
  52794. // traverse graph per trigger
  52795. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52796. if (combineArray === void 0) { combineArray = null; }
  52797. if (parsedAction.detached)
  52798. return;
  52799. var parameters = new Array();
  52800. var target = null;
  52801. var propertyPath = null;
  52802. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52803. // Parameters
  52804. if (parsedAction.type === 2)
  52805. parameters.push(actionManager);
  52806. else
  52807. parameters.push(trigger);
  52808. if (combine) {
  52809. var actions = new Array();
  52810. for (var j = 0; j < parsedAction.combine.length; j++) {
  52811. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52812. }
  52813. parameters.push(actions);
  52814. }
  52815. else {
  52816. for (var i = 0; i < parsedAction.properties.length; i++) {
  52817. var value = parsedAction.properties[i].value;
  52818. var name = parsedAction.properties[i].name;
  52819. var targetType = parsedAction.properties[i].targetType;
  52820. if (name === "target")
  52821. if (targetType !== null && targetType === "SceneProperties")
  52822. value = target = scene;
  52823. else
  52824. value = target = scene.getNodeByName(value);
  52825. else if (name === "parent")
  52826. value = scene.getNodeByName(value);
  52827. else if (name === "sound")
  52828. value = scene.getSoundByName(value);
  52829. else if (name !== "propertyPath") {
  52830. if (parsedAction.type === 2 && name === "operator")
  52831. value = BABYLON.ValueCondition[value];
  52832. else
  52833. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52834. }
  52835. else {
  52836. propertyPath = value;
  52837. }
  52838. parameters.push(value);
  52839. }
  52840. }
  52841. if (combineArray === null) {
  52842. parameters.push(condition);
  52843. }
  52844. else {
  52845. parameters.push(null);
  52846. }
  52847. // If interpolate value action
  52848. if (parsedAction.name === "InterpolateValueAction") {
  52849. var param = parameters[parameters.length - 2];
  52850. parameters[parameters.length - 1] = param;
  52851. parameters[parameters.length - 2] = condition;
  52852. }
  52853. // Action or condition(s) and not CombineAction
  52854. var newAction = instanciate(parsedAction.name, parameters);
  52855. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52856. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52857. if (action)
  52858. action.then(nothing);
  52859. else
  52860. actionManager.registerAction(nothing);
  52861. action = nothing;
  52862. }
  52863. if (combineArray === null) {
  52864. if (newAction instanceof BABYLON.Condition) {
  52865. condition = newAction;
  52866. newAction = action;
  52867. }
  52868. else {
  52869. condition = null;
  52870. if (action)
  52871. action.then(newAction);
  52872. else
  52873. actionManager.registerAction(newAction);
  52874. }
  52875. }
  52876. else {
  52877. combineArray.push(newAction);
  52878. }
  52879. for (var i = 0; i < parsedAction.children.length; i++)
  52880. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52881. };
  52882. // triggers
  52883. for (var i = 0; i < parsedActions.children.length; i++) {
  52884. var triggerParams;
  52885. var trigger = parsedActions.children[i];
  52886. if (trigger.properties.length > 0) {
  52887. var param = trigger.properties[0].value;
  52888. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52889. if (value._meshId) {
  52890. value.mesh = scene.getMeshByID(value._meshId);
  52891. }
  52892. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52893. }
  52894. else
  52895. triggerParams = ActionManager[trigger.name];
  52896. for (var j = 0; j < trigger.children.length; j++) {
  52897. if (!trigger.detached)
  52898. traverse(trigger.children[j], triggerParams, null, null);
  52899. }
  52900. }
  52901. };
  52902. /**
  52903. * Get a trigger name by index
  52904. * @param trigger defines the trigger index
  52905. * @returns a trigger name
  52906. */
  52907. ActionManager.GetTriggerName = function (trigger) {
  52908. switch (trigger) {
  52909. case 0: return "NothingTrigger";
  52910. case 1: return "OnPickTrigger";
  52911. case 2: return "OnLeftPickTrigger";
  52912. case 3: return "OnRightPickTrigger";
  52913. case 4: return "OnCenterPickTrigger";
  52914. case 5: return "OnPickDownTrigger";
  52915. case 6: return "OnPickUpTrigger";
  52916. case 7: return "OnLongPressTrigger";
  52917. case 8: return "OnPointerOverTrigger";
  52918. case 9: return "OnPointerOutTrigger";
  52919. case 10: return "OnEveryFrameTrigger";
  52920. case 11: return "OnIntersectionEnterTrigger";
  52921. case 12: return "OnIntersectionExitTrigger";
  52922. case 13: return "OnKeyDownTrigger";
  52923. case 14: return "OnKeyUpTrigger";
  52924. case 15: return "OnPickOutTrigger";
  52925. default: return "";
  52926. }
  52927. };
  52928. // Statics
  52929. ActionManager._NothingTrigger = 0;
  52930. ActionManager._OnPickTrigger = 1;
  52931. ActionManager._OnLeftPickTrigger = 2;
  52932. ActionManager._OnRightPickTrigger = 3;
  52933. ActionManager._OnCenterPickTrigger = 4;
  52934. ActionManager._OnPickDownTrigger = 5;
  52935. ActionManager._OnDoublePickTrigger = 6;
  52936. ActionManager._OnPickUpTrigger = 7;
  52937. ActionManager._OnLongPressTrigger = 8;
  52938. ActionManager._OnPointerOverTrigger = 9;
  52939. ActionManager._OnPointerOutTrigger = 10;
  52940. ActionManager._OnEveryFrameTrigger = 11;
  52941. ActionManager._OnIntersectionEnterTrigger = 12;
  52942. ActionManager._OnIntersectionExitTrigger = 13;
  52943. ActionManager._OnKeyDownTrigger = 14;
  52944. ActionManager._OnKeyUpTrigger = 15;
  52945. ActionManager._OnPickOutTrigger = 16;
  52946. /** Gets the list of active triggers */
  52947. ActionManager.Triggers = {};
  52948. return ActionManager;
  52949. }());
  52950. BABYLON.ActionManager = ActionManager;
  52951. })(BABYLON || (BABYLON = {}));
  52952. //# sourceMappingURL=babylon.actionManager.js.map
  52953. var BABYLON;
  52954. (function (BABYLON) {
  52955. var InterpolateValueAction = /** @class */ (function (_super) {
  52956. __extends(InterpolateValueAction, _super);
  52957. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52958. if (duration === void 0) { duration = 1000; }
  52959. var _this = _super.call(this, triggerOptions, condition) || this;
  52960. _this.propertyPath = propertyPath;
  52961. _this.value = value;
  52962. _this.duration = duration;
  52963. _this.stopOtherAnimations = stopOtherAnimations;
  52964. _this.onInterpolationDone = onInterpolationDone;
  52965. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52966. _this._target = _this._effectiveTarget = target;
  52967. return _this;
  52968. }
  52969. InterpolateValueAction.prototype._prepare = function () {
  52970. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52971. this._property = this._getProperty(this.propertyPath);
  52972. };
  52973. InterpolateValueAction.prototype.execute = function () {
  52974. var _this = this;
  52975. var scene = this._actionManager.getScene();
  52976. var keys = [
  52977. {
  52978. frame: 0,
  52979. value: this._effectiveTarget[this._property]
  52980. }, {
  52981. frame: 100,
  52982. value: this.value
  52983. }
  52984. ];
  52985. var dataType;
  52986. if (typeof this.value === "number") {
  52987. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52988. }
  52989. else if (this.value instanceof BABYLON.Color3) {
  52990. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52991. }
  52992. else if (this.value instanceof BABYLON.Vector3) {
  52993. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52994. }
  52995. else if (this.value instanceof BABYLON.Matrix) {
  52996. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52997. }
  52998. else if (this.value instanceof BABYLON.Quaternion) {
  52999. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53000. }
  53001. else {
  53002. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53003. return;
  53004. }
  53005. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53006. animation.setKeys(keys);
  53007. if (this.stopOtherAnimations) {
  53008. scene.stopAnimation(this._effectiveTarget);
  53009. }
  53010. var wrapper = function () {
  53011. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53012. if (_this.onInterpolationDone) {
  53013. _this.onInterpolationDone();
  53014. }
  53015. };
  53016. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53017. };
  53018. InterpolateValueAction.prototype.serialize = function (parent) {
  53019. return _super.prototype._serialize.call(this, {
  53020. name: "InterpolateValueAction",
  53021. properties: [
  53022. BABYLON.Action._GetTargetProperty(this._target),
  53023. { name: "propertyPath", value: this.propertyPath },
  53024. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53025. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53026. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53027. ]
  53028. }, parent);
  53029. };
  53030. return InterpolateValueAction;
  53031. }(BABYLON.Action));
  53032. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53033. })(BABYLON || (BABYLON = {}));
  53034. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53035. var BABYLON;
  53036. (function (BABYLON) {
  53037. var SwitchBooleanAction = /** @class */ (function (_super) {
  53038. __extends(SwitchBooleanAction, _super);
  53039. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53040. var _this = _super.call(this, triggerOptions, condition) || this;
  53041. _this.propertyPath = propertyPath;
  53042. _this._target = _this._effectiveTarget = target;
  53043. return _this;
  53044. }
  53045. SwitchBooleanAction.prototype._prepare = function () {
  53046. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53047. this._property = this._getProperty(this.propertyPath);
  53048. };
  53049. SwitchBooleanAction.prototype.execute = function () {
  53050. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53051. };
  53052. SwitchBooleanAction.prototype.serialize = function (parent) {
  53053. return _super.prototype._serialize.call(this, {
  53054. name: "SwitchBooleanAction",
  53055. properties: [
  53056. BABYLON.Action._GetTargetProperty(this._target),
  53057. { name: "propertyPath", value: this.propertyPath }
  53058. ]
  53059. }, parent);
  53060. };
  53061. return SwitchBooleanAction;
  53062. }(BABYLON.Action));
  53063. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53064. var SetStateAction = /** @class */ (function (_super) {
  53065. __extends(SetStateAction, _super);
  53066. function SetStateAction(triggerOptions, target, value, condition) {
  53067. var _this = _super.call(this, triggerOptions, condition) || this;
  53068. _this.value = value;
  53069. _this._target = target;
  53070. return _this;
  53071. }
  53072. SetStateAction.prototype.execute = function () {
  53073. this._target.state = this.value;
  53074. };
  53075. SetStateAction.prototype.serialize = function (parent) {
  53076. return _super.prototype._serialize.call(this, {
  53077. name: "SetStateAction",
  53078. properties: [
  53079. BABYLON.Action._GetTargetProperty(this._target),
  53080. { name: "value", value: this.value }
  53081. ]
  53082. }, parent);
  53083. };
  53084. return SetStateAction;
  53085. }(BABYLON.Action));
  53086. BABYLON.SetStateAction = SetStateAction;
  53087. var SetValueAction = /** @class */ (function (_super) {
  53088. __extends(SetValueAction, _super);
  53089. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53090. var _this = _super.call(this, triggerOptions, condition) || this;
  53091. _this.propertyPath = propertyPath;
  53092. _this.value = value;
  53093. _this._target = _this._effectiveTarget = target;
  53094. return _this;
  53095. }
  53096. SetValueAction.prototype._prepare = function () {
  53097. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53098. this._property = this._getProperty(this.propertyPath);
  53099. };
  53100. SetValueAction.prototype.execute = function () {
  53101. this._effectiveTarget[this._property] = this.value;
  53102. if (this._target.markAsDirty) {
  53103. this._target.markAsDirty(this._property);
  53104. }
  53105. };
  53106. SetValueAction.prototype.serialize = function (parent) {
  53107. return _super.prototype._serialize.call(this, {
  53108. name: "SetValueAction",
  53109. properties: [
  53110. BABYLON.Action._GetTargetProperty(this._target),
  53111. { name: "propertyPath", value: this.propertyPath },
  53112. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53113. ]
  53114. }, parent);
  53115. };
  53116. return SetValueAction;
  53117. }(BABYLON.Action));
  53118. BABYLON.SetValueAction = SetValueAction;
  53119. var IncrementValueAction = /** @class */ (function (_super) {
  53120. __extends(IncrementValueAction, _super);
  53121. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53122. var _this = _super.call(this, triggerOptions, condition) || this;
  53123. _this.propertyPath = propertyPath;
  53124. _this.value = value;
  53125. _this._target = _this._effectiveTarget = target;
  53126. return _this;
  53127. }
  53128. IncrementValueAction.prototype._prepare = function () {
  53129. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53130. this._property = this._getProperty(this.propertyPath);
  53131. if (typeof this._effectiveTarget[this._property] !== "number") {
  53132. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53133. }
  53134. };
  53135. IncrementValueAction.prototype.execute = function () {
  53136. this._effectiveTarget[this._property] += this.value;
  53137. if (this._target.markAsDirty) {
  53138. this._target.markAsDirty(this._property);
  53139. }
  53140. };
  53141. IncrementValueAction.prototype.serialize = function (parent) {
  53142. return _super.prototype._serialize.call(this, {
  53143. name: "IncrementValueAction",
  53144. properties: [
  53145. BABYLON.Action._GetTargetProperty(this._target),
  53146. { name: "propertyPath", value: this.propertyPath },
  53147. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53148. ]
  53149. }, parent);
  53150. };
  53151. return IncrementValueAction;
  53152. }(BABYLON.Action));
  53153. BABYLON.IncrementValueAction = IncrementValueAction;
  53154. var PlayAnimationAction = /** @class */ (function (_super) {
  53155. __extends(PlayAnimationAction, _super);
  53156. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53157. var _this = _super.call(this, triggerOptions, condition) || this;
  53158. _this.from = from;
  53159. _this.to = to;
  53160. _this.loop = loop;
  53161. _this._target = target;
  53162. return _this;
  53163. }
  53164. PlayAnimationAction.prototype._prepare = function () {
  53165. };
  53166. PlayAnimationAction.prototype.execute = function () {
  53167. var scene = this._actionManager.getScene();
  53168. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53169. };
  53170. PlayAnimationAction.prototype.serialize = function (parent) {
  53171. return _super.prototype._serialize.call(this, {
  53172. name: "PlayAnimationAction",
  53173. properties: [
  53174. BABYLON.Action._GetTargetProperty(this._target),
  53175. { name: "from", value: String(this.from) },
  53176. { name: "to", value: String(this.to) },
  53177. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53178. ]
  53179. }, parent);
  53180. };
  53181. return PlayAnimationAction;
  53182. }(BABYLON.Action));
  53183. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53184. var StopAnimationAction = /** @class */ (function (_super) {
  53185. __extends(StopAnimationAction, _super);
  53186. function StopAnimationAction(triggerOptions, target, condition) {
  53187. var _this = _super.call(this, triggerOptions, condition) || this;
  53188. _this._target = target;
  53189. return _this;
  53190. }
  53191. StopAnimationAction.prototype._prepare = function () {
  53192. };
  53193. StopAnimationAction.prototype.execute = function () {
  53194. var scene = this._actionManager.getScene();
  53195. scene.stopAnimation(this._target);
  53196. };
  53197. StopAnimationAction.prototype.serialize = function (parent) {
  53198. return _super.prototype._serialize.call(this, {
  53199. name: "StopAnimationAction",
  53200. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53201. }, parent);
  53202. };
  53203. return StopAnimationAction;
  53204. }(BABYLON.Action));
  53205. BABYLON.StopAnimationAction = StopAnimationAction;
  53206. var DoNothingAction = /** @class */ (function (_super) {
  53207. __extends(DoNothingAction, _super);
  53208. function DoNothingAction(triggerOptions, condition) {
  53209. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53210. return _super.call(this, triggerOptions, condition) || this;
  53211. }
  53212. DoNothingAction.prototype.execute = function () {
  53213. };
  53214. DoNothingAction.prototype.serialize = function (parent) {
  53215. return _super.prototype._serialize.call(this, {
  53216. name: "DoNothingAction",
  53217. properties: []
  53218. }, parent);
  53219. };
  53220. return DoNothingAction;
  53221. }(BABYLON.Action));
  53222. BABYLON.DoNothingAction = DoNothingAction;
  53223. var CombineAction = /** @class */ (function (_super) {
  53224. __extends(CombineAction, _super);
  53225. function CombineAction(triggerOptions, children, condition) {
  53226. var _this = _super.call(this, triggerOptions, condition) || this;
  53227. _this.children = children;
  53228. return _this;
  53229. }
  53230. CombineAction.prototype._prepare = function () {
  53231. for (var index = 0; index < this.children.length; index++) {
  53232. this.children[index]._actionManager = this._actionManager;
  53233. this.children[index]._prepare();
  53234. }
  53235. };
  53236. CombineAction.prototype.execute = function (evt) {
  53237. for (var index = 0; index < this.children.length; index++) {
  53238. this.children[index].execute(evt);
  53239. }
  53240. };
  53241. CombineAction.prototype.serialize = function (parent) {
  53242. var serializationObject = _super.prototype._serialize.call(this, {
  53243. name: "CombineAction",
  53244. properties: [],
  53245. combine: []
  53246. }, parent);
  53247. for (var i = 0; i < this.children.length; i++) {
  53248. serializationObject.combine.push(this.children[i].serialize(null));
  53249. }
  53250. return serializationObject;
  53251. };
  53252. return CombineAction;
  53253. }(BABYLON.Action));
  53254. BABYLON.CombineAction = CombineAction;
  53255. var ExecuteCodeAction = /** @class */ (function (_super) {
  53256. __extends(ExecuteCodeAction, _super);
  53257. function ExecuteCodeAction(triggerOptions, func, condition) {
  53258. var _this = _super.call(this, triggerOptions, condition) || this;
  53259. _this.func = func;
  53260. return _this;
  53261. }
  53262. ExecuteCodeAction.prototype.execute = function (evt) {
  53263. this.func(evt);
  53264. };
  53265. return ExecuteCodeAction;
  53266. }(BABYLON.Action));
  53267. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53268. var SetParentAction = /** @class */ (function (_super) {
  53269. __extends(SetParentAction, _super);
  53270. function SetParentAction(triggerOptions, target, parent, condition) {
  53271. var _this = _super.call(this, triggerOptions, condition) || this;
  53272. _this._target = target;
  53273. _this._parent = parent;
  53274. return _this;
  53275. }
  53276. SetParentAction.prototype._prepare = function () {
  53277. };
  53278. SetParentAction.prototype.execute = function () {
  53279. if (this._target.parent === this._parent) {
  53280. return;
  53281. }
  53282. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53283. invertParentWorldMatrix.invert();
  53284. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53285. this._target.parent = this._parent;
  53286. };
  53287. SetParentAction.prototype.serialize = function (parent) {
  53288. return _super.prototype._serialize.call(this, {
  53289. name: "SetParentAction",
  53290. properties: [
  53291. BABYLON.Action._GetTargetProperty(this._target),
  53292. BABYLON.Action._GetTargetProperty(this._parent),
  53293. ]
  53294. }, parent);
  53295. };
  53296. return SetParentAction;
  53297. }(BABYLON.Action));
  53298. BABYLON.SetParentAction = SetParentAction;
  53299. var PlaySoundAction = /** @class */ (function (_super) {
  53300. __extends(PlaySoundAction, _super);
  53301. function PlaySoundAction(triggerOptions, sound, condition) {
  53302. var _this = _super.call(this, triggerOptions, condition) || this;
  53303. _this._sound = sound;
  53304. return _this;
  53305. }
  53306. PlaySoundAction.prototype._prepare = function () {
  53307. };
  53308. PlaySoundAction.prototype.execute = function () {
  53309. if (this._sound !== undefined)
  53310. this._sound.play();
  53311. };
  53312. PlaySoundAction.prototype.serialize = function (parent) {
  53313. return _super.prototype._serialize.call(this, {
  53314. name: "PlaySoundAction",
  53315. properties: [{ name: "sound", value: this._sound.name }]
  53316. }, parent);
  53317. };
  53318. return PlaySoundAction;
  53319. }(BABYLON.Action));
  53320. BABYLON.PlaySoundAction = PlaySoundAction;
  53321. var StopSoundAction = /** @class */ (function (_super) {
  53322. __extends(StopSoundAction, _super);
  53323. function StopSoundAction(triggerOptions, sound, condition) {
  53324. var _this = _super.call(this, triggerOptions, condition) || this;
  53325. _this._sound = sound;
  53326. return _this;
  53327. }
  53328. StopSoundAction.prototype._prepare = function () {
  53329. };
  53330. StopSoundAction.prototype.execute = function () {
  53331. if (this._sound !== undefined)
  53332. this._sound.stop();
  53333. };
  53334. StopSoundAction.prototype.serialize = function (parent) {
  53335. return _super.prototype._serialize.call(this, {
  53336. name: "StopSoundAction",
  53337. properties: [{ name: "sound", value: this._sound.name }]
  53338. }, parent);
  53339. };
  53340. return StopSoundAction;
  53341. }(BABYLON.Action));
  53342. BABYLON.StopSoundAction = StopSoundAction;
  53343. })(BABYLON || (BABYLON = {}));
  53344. //# sourceMappingURL=babylon.directActions.js.map
  53345. var BABYLON;
  53346. (function (BABYLON) {
  53347. var SpriteManager = /** @class */ (function () {
  53348. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53349. if (epsilon === void 0) { epsilon = 0.01; }
  53350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53351. this.name = name;
  53352. this.sprites = new Array();
  53353. this.renderingGroupId = 0;
  53354. this.layerMask = 0x0FFFFFFF;
  53355. this.fogEnabled = true;
  53356. this.isPickable = false;
  53357. /**
  53358. * An event triggered when the manager is disposed.
  53359. */
  53360. this.onDisposeObservable = new BABYLON.Observable();
  53361. this._vertexBuffers = {};
  53362. this._capacity = capacity;
  53363. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53364. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53365. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53366. if (cellSize.width && cellSize.height) {
  53367. this.cellWidth = cellSize.width;
  53368. this.cellHeight = cellSize.height;
  53369. }
  53370. else if (cellSize !== undefined) {
  53371. this.cellWidth = cellSize;
  53372. this.cellHeight = cellSize;
  53373. }
  53374. else {
  53375. return;
  53376. }
  53377. this._epsilon = epsilon;
  53378. this._scene = scene;
  53379. this._scene.spriteManagers.push(this);
  53380. var indices = [];
  53381. var index = 0;
  53382. for (var count = 0; count < capacity; count++) {
  53383. indices.push(index);
  53384. indices.push(index + 1);
  53385. indices.push(index + 2);
  53386. indices.push(index);
  53387. indices.push(index + 2);
  53388. indices.push(index + 3);
  53389. index += 4;
  53390. }
  53391. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53392. // VBO
  53393. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53394. this._vertexData = new Float32Array(capacity * 16 * 4);
  53395. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53396. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53397. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53398. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53399. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53400. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53401. this._vertexBuffers["options"] = options;
  53402. this._vertexBuffers["cellInfo"] = cellInfo;
  53403. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53404. // Effects
  53405. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53406. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53407. }
  53408. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53409. set: function (callback) {
  53410. if (this._onDisposeObserver) {
  53411. this.onDisposeObservable.remove(this._onDisposeObserver);
  53412. }
  53413. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53414. },
  53415. enumerable: true,
  53416. configurable: true
  53417. });
  53418. Object.defineProperty(SpriteManager.prototype, "texture", {
  53419. get: function () {
  53420. return this._spriteTexture;
  53421. },
  53422. set: function (value) {
  53423. this._spriteTexture = value;
  53424. },
  53425. enumerable: true,
  53426. configurable: true
  53427. });
  53428. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53429. var arrayOffset = index * 16;
  53430. if (offsetX === 0)
  53431. offsetX = this._epsilon;
  53432. else if (offsetX === 1)
  53433. offsetX = 1 - this._epsilon;
  53434. if (offsetY === 0)
  53435. offsetY = this._epsilon;
  53436. else if (offsetY === 1)
  53437. offsetY = 1 - this._epsilon;
  53438. this._vertexData[arrayOffset] = sprite.position.x;
  53439. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53440. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53441. this._vertexData[arrayOffset + 3] = sprite.angle;
  53442. this._vertexData[arrayOffset + 4] = sprite.width;
  53443. this._vertexData[arrayOffset + 5] = sprite.height;
  53444. this._vertexData[arrayOffset + 6] = offsetX;
  53445. this._vertexData[arrayOffset + 7] = offsetY;
  53446. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53447. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53448. var offset = (sprite.cellIndex / rowSize) >> 0;
  53449. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53450. this._vertexData[arrayOffset + 11] = offset;
  53451. // Color
  53452. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53453. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53454. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53455. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53456. };
  53457. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53458. var count = Math.min(this._capacity, this.sprites.length);
  53459. var min = BABYLON.Vector3.Zero();
  53460. var max = BABYLON.Vector3.Zero();
  53461. var distance = Number.MAX_VALUE;
  53462. var currentSprite = null;
  53463. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53464. var cameraView = camera.getViewMatrix();
  53465. for (var index = 0; index < count; index++) {
  53466. var sprite = this.sprites[index];
  53467. if (!sprite) {
  53468. continue;
  53469. }
  53470. if (predicate) {
  53471. if (!predicate(sprite)) {
  53472. continue;
  53473. }
  53474. }
  53475. else if (!sprite.isPickable) {
  53476. continue;
  53477. }
  53478. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53479. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53480. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53481. if (ray.intersectsBoxMinMax(min, max)) {
  53482. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53483. if (distance > currentDistance) {
  53484. distance = currentDistance;
  53485. currentSprite = sprite;
  53486. if (fastCheck) {
  53487. break;
  53488. }
  53489. }
  53490. }
  53491. }
  53492. if (currentSprite) {
  53493. var result = new BABYLON.PickingInfo();
  53494. result.hit = true;
  53495. result.pickedSprite = currentSprite;
  53496. result.distance = distance;
  53497. return result;
  53498. }
  53499. return null;
  53500. };
  53501. SpriteManager.prototype.render = function () {
  53502. // Check
  53503. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53504. return;
  53505. var engine = this._scene.getEngine();
  53506. var baseSize = this._spriteTexture.getBaseSize();
  53507. // Sprites
  53508. var deltaTime = engine.getDeltaTime();
  53509. var max = Math.min(this._capacity, this.sprites.length);
  53510. var rowSize = baseSize.width / this.cellWidth;
  53511. var offset = 0;
  53512. for (var index = 0; index < max; index++) {
  53513. var sprite = this.sprites[index];
  53514. if (!sprite || !sprite.isVisible) {
  53515. continue;
  53516. }
  53517. sprite._animate(deltaTime);
  53518. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53519. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53520. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53521. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53522. }
  53523. this._buffer.update(this._vertexData);
  53524. // Render
  53525. var effect = this._effectBase;
  53526. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53527. effect = this._effectFog;
  53528. }
  53529. engine.enableEffect(effect);
  53530. var viewMatrix = this._scene.getViewMatrix();
  53531. effect.setTexture("diffuseSampler", this._spriteTexture);
  53532. effect.setMatrix("view", viewMatrix);
  53533. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53534. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53535. // Fog
  53536. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53537. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53538. effect.setColor3("vFogColor", this._scene.fogColor);
  53539. }
  53540. // VBOs
  53541. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53542. // Draw order
  53543. engine.setDepthFunctionToLessOrEqual();
  53544. effect.setBool("alphaTest", true);
  53545. engine.setColorWrite(false);
  53546. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53547. engine.setColorWrite(true);
  53548. effect.setBool("alphaTest", false);
  53549. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53550. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53551. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53552. };
  53553. SpriteManager.prototype.dispose = function () {
  53554. if (this._buffer) {
  53555. this._buffer.dispose();
  53556. this._buffer = null;
  53557. }
  53558. if (this._indexBuffer) {
  53559. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53560. this._indexBuffer = null;
  53561. }
  53562. if (this._spriteTexture) {
  53563. this._spriteTexture.dispose();
  53564. this._spriteTexture = null;
  53565. }
  53566. // Remove from scene
  53567. var index = this._scene.spriteManagers.indexOf(this);
  53568. this._scene.spriteManagers.splice(index, 1);
  53569. // Callback
  53570. this.onDisposeObservable.notifyObservers(this);
  53571. this.onDisposeObservable.clear();
  53572. };
  53573. return SpriteManager;
  53574. }());
  53575. BABYLON.SpriteManager = SpriteManager;
  53576. })(BABYLON || (BABYLON = {}));
  53577. //# sourceMappingURL=babylon.spriteManager.js.map
  53578. var BABYLON;
  53579. (function (BABYLON) {
  53580. var Sprite = /** @class */ (function () {
  53581. function Sprite(name, manager) {
  53582. this.name = name;
  53583. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53584. this.width = 1.0;
  53585. this.height = 1.0;
  53586. this.angle = 0;
  53587. this.cellIndex = 0;
  53588. this.invertU = 0;
  53589. this.invertV = 0;
  53590. this.animations = new Array();
  53591. this.isPickable = false;
  53592. this._animationStarted = false;
  53593. this._loopAnimation = false;
  53594. this._fromIndex = 0;
  53595. this._toIndex = 0;
  53596. this._delay = 0;
  53597. this._direction = 1;
  53598. this._time = 0;
  53599. /**
  53600. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53601. */
  53602. this.isVisible = true;
  53603. this._manager = manager;
  53604. this._manager.sprites.push(this);
  53605. this.position = BABYLON.Vector3.Zero();
  53606. }
  53607. Object.defineProperty(Sprite.prototype, "size", {
  53608. get: function () {
  53609. return this.width;
  53610. },
  53611. set: function (value) {
  53612. this.width = value;
  53613. this.height = value;
  53614. },
  53615. enumerable: true,
  53616. configurable: true
  53617. });
  53618. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53619. this._fromIndex = from;
  53620. this._toIndex = to;
  53621. this._loopAnimation = loop;
  53622. this._delay = delay;
  53623. this._animationStarted = true;
  53624. this._direction = from < to ? 1 : -1;
  53625. this.cellIndex = from;
  53626. this._time = 0;
  53627. this._onAnimationEnd = onAnimationEnd;
  53628. };
  53629. Sprite.prototype.stopAnimation = function () {
  53630. this._animationStarted = false;
  53631. };
  53632. Sprite.prototype._animate = function (deltaTime) {
  53633. if (!this._animationStarted)
  53634. return;
  53635. this._time += deltaTime;
  53636. if (this._time > this._delay) {
  53637. this._time = this._time % this._delay;
  53638. this.cellIndex += this._direction;
  53639. if (this.cellIndex > this._toIndex) {
  53640. if (this._loopAnimation) {
  53641. this.cellIndex = this._fromIndex;
  53642. }
  53643. else {
  53644. this.cellIndex = this._toIndex;
  53645. this._animationStarted = false;
  53646. if (this._onAnimationEnd) {
  53647. this._onAnimationEnd();
  53648. }
  53649. if (this.disposeWhenFinishedAnimating) {
  53650. this.dispose();
  53651. }
  53652. }
  53653. }
  53654. }
  53655. };
  53656. Sprite.prototype.dispose = function () {
  53657. for (var i = 0; i < this._manager.sprites.length; i++) {
  53658. if (this._manager.sprites[i] == this) {
  53659. this._manager.sprites.splice(i, 1);
  53660. }
  53661. }
  53662. };
  53663. return Sprite;
  53664. }());
  53665. BABYLON.Sprite = Sprite;
  53666. })(BABYLON || (BABYLON = {}));
  53667. //# sourceMappingURL=babylon.sprite.js.map
  53668. var BABYLON;
  53669. (function (BABYLON) {
  53670. var IntersectionInfo = /** @class */ (function () {
  53671. function IntersectionInfo(bu, bv, distance) {
  53672. this.bu = bu;
  53673. this.bv = bv;
  53674. this.distance = distance;
  53675. this.faceId = 0;
  53676. this.subMeshId = 0;
  53677. }
  53678. return IntersectionInfo;
  53679. }());
  53680. BABYLON.IntersectionInfo = IntersectionInfo;
  53681. /**
  53682. * Information about the result of picking within a scene
  53683. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53684. */
  53685. var PickingInfo = /** @class */ (function () {
  53686. function PickingInfo() {
  53687. /**
  53688. * If the pick collided with an object
  53689. */
  53690. this.hit = false;
  53691. /**
  53692. * Distance away where the pick collided
  53693. */
  53694. this.distance = 0;
  53695. /**
  53696. * The location of pick collision
  53697. */
  53698. this.pickedPoint = null;
  53699. /**
  53700. * The mesh corrisponding the the pick collision
  53701. */
  53702. this.pickedMesh = null;
  53703. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53704. this.bu = 0;
  53705. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53706. this.bv = 0;
  53707. /** The id of the face on the mesh that was picked */
  53708. this.faceId = -1;
  53709. /** Id of the the submesh that was picked */
  53710. this.subMeshId = 0;
  53711. /** If a sprite was picked, this will be the sprite the pick collided with */
  53712. this.pickedSprite = null;
  53713. /**
  53714. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53715. */
  53716. this.originMesh = null;
  53717. /**
  53718. * The ray that was used to perform the picking.
  53719. */
  53720. this.ray = null;
  53721. }
  53722. /**
  53723. * Gets the normal corrispodning to the face the pick collided with
  53724. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53725. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53726. * @returns The normal corrispodning to the face the pick collided with
  53727. */
  53728. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53729. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53730. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53731. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53732. return null;
  53733. }
  53734. var indices = this.pickedMesh.getIndices();
  53735. if (!indices) {
  53736. return null;
  53737. }
  53738. var result;
  53739. if (useVerticesNormals) {
  53740. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53741. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53742. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53743. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53744. normal0 = normal0.scale(this.bu);
  53745. normal1 = normal1.scale(this.bv);
  53746. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53747. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53748. }
  53749. else {
  53750. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53751. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53752. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53753. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53754. var p1p2 = vertex1.subtract(vertex2);
  53755. var p3p2 = vertex3.subtract(vertex2);
  53756. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53757. }
  53758. if (useWorldCoordinates) {
  53759. var wm = this.pickedMesh.getWorldMatrix();
  53760. if (this.pickedMesh.nonUniformScaling) {
  53761. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53762. wm = BABYLON.Tmp.Matrix[0];
  53763. wm.setTranslationFromFloats(0, 0, 0);
  53764. wm.invert();
  53765. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53766. wm = BABYLON.Tmp.Matrix[1];
  53767. }
  53768. result = BABYLON.Vector3.TransformNormal(result, wm);
  53769. }
  53770. result.normalize();
  53771. return result;
  53772. };
  53773. /**
  53774. * Gets the texture coordinates of where the pick occured
  53775. * @returns the vector containing the coordnates of the texture
  53776. */
  53777. PickingInfo.prototype.getTextureCoordinates = function () {
  53778. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53779. return null;
  53780. }
  53781. var indices = this.pickedMesh.getIndices();
  53782. if (!indices) {
  53783. return null;
  53784. }
  53785. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53786. if (!uvs) {
  53787. return null;
  53788. }
  53789. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53790. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53791. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53792. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53793. uv1 = uv1.scale(this.bu);
  53794. uv2 = uv2.scale(this.bv);
  53795. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53796. };
  53797. return PickingInfo;
  53798. }());
  53799. BABYLON.PickingInfo = PickingInfo;
  53800. })(BABYLON || (BABYLON = {}));
  53801. //# sourceMappingURL=babylon.pickingInfo.js.map
  53802. var BABYLON;
  53803. (function (BABYLON) {
  53804. var Ray = /** @class */ (function () {
  53805. function Ray(origin, direction, length) {
  53806. if (length === void 0) { length = Number.MAX_VALUE; }
  53807. this.origin = origin;
  53808. this.direction = direction;
  53809. this.length = length;
  53810. }
  53811. // Methods
  53812. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53813. var d = 0.0;
  53814. var maxValue = Number.MAX_VALUE;
  53815. var inv;
  53816. var min;
  53817. var max;
  53818. var temp;
  53819. if (Math.abs(this.direction.x) < 0.0000001) {
  53820. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53821. return false;
  53822. }
  53823. }
  53824. else {
  53825. inv = 1.0 / this.direction.x;
  53826. min = (minimum.x - this.origin.x) * inv;
  53827. max = (maximum.x - this.origin.x) * inv;
  53828. if (max === -Infinity) {
  53829. max = Infinity;
  53830. }
  53831. if (min > max) {
  53832. temp = min;
  53833. min = max;
  53834. max = temp;
  53835. }
  53836. d = Math.max(min, d);
  53837. maxValue = Math.min(max, maxValue);
  53838. if (d > maxValue) {
  53839. return false;
  53840. }
  53841. }
  53842. if (Math.abs(this.direction.y) < 0.0000001) {
  53843. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53844. return false;
  53845. }
  53846. }
  53847. else {
  53848. inv = 1.0 / this.direction.y;
  53849. min = (minimum.y - this.origin.y) * inv;
  53850. max = (maximum.y - this.origin.y) * inv;
  53851. if (max === -Infinity) {
  53852. max = Infinity;
  53853. }
  53854. if (min > max) {
  53855. temp = min;
  53856. min = max;
  53857. max = temp;
  53858. }
  53859. d = Math.max(min, d);
  53860. maxValue = Math.min(max, maxValue);
  53861. if (d > maxValue) {
  53862. return false;
  53863. }
  53864. }
  53865. if (Math.abs(this.direction.z) < 0.0000001) {
  53866. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53867. return false;
  53868. }
  53869. }
  53870. else {
  53871. inv = 1.0 / this.direction.z;
  53872. min = (minimum.z - this.origin.z) * inv;
  53873. max = (maximum.z - this.origin.z) * inv;
  53874. if (max === -Infinity) {
  53875. max = Infinity;
  53876. }
  53877. if (min > max) {
  53878. temp = min;
  53879. min = max;
  53880. max = temp;
  53881. }
  53882. d = Math.max(min, d);
  53883. maxValue = Math.min(max, maxValue);
  53884. if (d > maxValue) {
  53885. return false;
  53886. }
  53887. }
  53888. return true;
  53889. };
  53890. Ray.prototype.intersectsBox = function (box) {
  53891. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53892. };
  53893. Ray.prototype.intersectsSphere = function (sphere) {
  53894. var x = sphere.center.x - this.origin.x;
  53895. var y = sphere.center.y - this.origin.y;
  53896. var z = sphere.center.z - this.origin.z;
  53897. var pyth = (x * x) + (y * y) + (z * z);
  53898. var rr = sphere.radius * sphere.radius;
  53899. if (pyth <= rr) {
  53900. return true;
  53901. }
  53902. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53903. if (dot < 0.0) {
  53904. return false;
  53905. }
  53906. var temp = pyth - (dot * dot);
  53907. return temp <= rr;
  53908. };
  53909. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53910. if (!this._edge1) {
  53911. this._edge1 = BABYLON.Vector3.Zero();
  53912. this._edge2 = BABYLON.Vector3.Zero();
  53913. this._pvec = BABYLON.Vector3.Zero();
  53914. this._tvec = BABYLON.Vector3.Zero();
  53915. this._qvec = BABYLON.Vector3.Zero();
  53916. }
  53917. vertex1.subtractToRef(vertex0, this._edge1);
  53918. vertex2.subtractToRef(vertex0, this._edge2);
  53919. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53920. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53921. if (det === 0) {
  53922. return null;
  53923. }
  53924. var invdet = 1 / det;
  53925. this.origin.subtractToRef(vertex0, this._tvec);
  53926. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53927. if (bu < 0 || bu > 1.0) {
  53928. return null;
  53929. }
  53930. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53931. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53932. if (bv < 0 || bu + bv > 1.0) {
  53933. return null;
  53934. }
  53935. //check if the distance is longer than the predefined length.
  53936. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53937. if (distance > this.length) {
  53938. return null;
  53939. }
  53940. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53941. };
  53942. Ray.prototype.intersectsPlane = function (plane) {
  53943. var distance;
  53944. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53945. if (Math.abs(result1) < 9.99999997475243E-07) {
  53946. return null;
  53947. }
  53948. else {
  53949. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53950. distance = (-plane.d - result2) / result1;
  53951. if (distance < 0.0) {
  53952. if (distance < -9.99999997475243E-07) {
  53953. return null;
  53954. }
  53955. else {
  53956. return 0;
  53957. }
  53958. }
  53959. return distance;
  53960. }
  53961. };
  53962. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53963. var tm = BABYLON.Tmp.Matrix[0];
  53964. mesh.getWorldMatrix().invertToRef(tm);
  53965. if (this._tmpRay) {
  53966. Ray.TransformToRef(this, tm, this._tmpRay);
  53967. }
  53968. else {
  53969. this._tmpRay = Ray.Transform(this, tm);
  53970. }
  53971. return mesh.intersects(this._tmpRay, fastCheck);
  53972. };
  53973. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53974. if (results) {
  53975. results.length = 0;
  53976. }
  53977. else {
  53978. results = [];
  53979. }
  53980. for (var i = 0; i < meshes.length; i++) {
  53981. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53982. if (pickInfo.hit) {
  53983. results.push(pickInfo);
  53984. }
  53985. }
  53986. results.sort(this._comparePickingInfo);
  53987. return results;
  53988. };
  53989. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53990. if (pickingInfoA.distance < pickingInfoB.distance) {
  53991. return -1;
  53992. }
  53993. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53994. return 1;
  53995. }
  53996. else {
  53997. return 0;
  53998. }
  53999. };
  54000. /**
  54001. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54002. * @param sega the first point of the segment to test the intersection against
  54003. * @param segb the second point of the segment to test the intersection against
  54004. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54005. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54006. */
  54007. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54008. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54009. var u = segb.subtract(sega);
  54010. var v = rsegb.subtract(this.origin);
  54011. var w = sega.subtract(this.origin);
  54012. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54013. var b = BABYLON.Vector3.Dot(u, v);
  54014. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54015. var d = BABYLON.Vector3.Dot(u, w);
  54016. var e = BABYLON.Vector3.Dot(v, w);
  54017. var D = a * c - b * b; // always >= 0
  54018. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54019. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54020. // compute the line parameters of the two closest points
  54021. if (D < Ray.smallnum) { // the lines are almost parallel
  54022. sN = 0.0; // force using point P0 on segment S1
  54023. sD = 1.0; // to prevent possible division by 0.0 later
  54024. tN = e;
  54025. tD = c;
  54026. }
  54027. else { // get the closest points on the infinite lines
  54028. sN = (b * e - c * d);
  54029. tN = (a * e - b * d);
  54030. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54031. sN = 0.0;
  54032. tN = e;
  54033. tD = c;
  54034. }
  54035. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54036. sN = sD;
  54037. tN = e + b;
  54038. tD = c;
  54039. }
  54040. }
  54041. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54042. tN = 0.0;
  54043. // recompute sc for this edge
  54044. if (-d < 0.0) {
  54045. sN = 0.0;
  54046. }
  54047. else if (-d > a)
  54048. sN = sD;
  54049. else {
  54050. sN = -d;
  54051. sD = a;
  54052. }
  54053. }
  54054. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54055. tN = tD;
  54056. // recompute sc for this edge
  54057. if ((-d + b) < 0.0) {
  54058. sN = 0;
  54059. }
  54060. else if ((-d + b) > a) {
  54061. sN = sD;
  54062. }
  54063. else {
  54064. sN = (-d + b);
  54065. sD = a;
  54066. }
  54067. }
  54068. // finally do the division to get sc and tc
  54069. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54070. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54071. // get the difference of the two closest points
  54072. var qtc = v.multiplyByFloats(tc, tc, tc);
  54073. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54074. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54075. if (isIntersected) {
  54076. return qtc.length();
  54077. }
  54078. return -1;
  54079. };
  54080. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54081. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54082. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54083. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54084. this.direction.normalize();
  54085. return this;
  54086. };
  54087. // Statics
  54088. Ray.Zero = function () {
  54089. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54090. };
  54091. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54092. var result = Ray.Zero();
  54093. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54094. };
  54095. /**
  54096. * 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
  54097. * transformed to the given world matrix.
  54098. * @param origin The origin point
  54099. * @param end The end point
  54100. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54101. */
  54102. Ray.CreateNewFromTo = function (origin, end, world) {
  54103. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54104. var direction = end.subtract(origin);
  54105. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54106. direction.normalize();
  54107. return Ray.Transform(new Ray(origin, direction, length), world);
  54108. };
  54109. Ray.Transform = function (ray, matrix) {
  54110. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54111. Ray.TransformToRef(ray, matrix, result);
  54112. return result;
  54113. };
  54114. Ray.TransformToRef = function (ray, matrix, result) {
  54115. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54116. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54117. result.length = ray.length;
  54118. var dir = result.direction;
  54119. var len = dir.length();
  54120. if (!(len === 0 || len === 1)) {
  54121. var num = 1.0 / len;
  54122. dir.x *= num;
  54123. dir.y *= num;
  54124. dir.z *= num;
  54125. result.length *= len;
  54126. }
  54127. };
  54128. Ray.smallnum = 0.00000001;
  54129. Ray.rayl = 10e8;
  54130. return Ray;
  54131. }());
  54132. BABYLON.Ray = Ray;
  54133. })(BABYLON || (BABYLON = {}));
  54134. //# sourceMappingURL=babylon.ray.js.map
  54135. var BABYLON;
  54136. (function (BABYLON) {
  54137. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54138. if (boxMin.x > sphereCenter.x + sphereRadius)
  54139. return false;
  54140. if (sphereCenter.x - sphereRadius > boxMax.x)
  54141. return false;
  54142. if (boxMin.y > sphereCenter.y + sphereRadius)
  54143. return false;
  54144. if (sphereCenter.y - sphereRadius > boxMax.y)
  54145. return false;
  54146. if (boxMin.z > sphereCenter.z + sphereRadius)
  54147. return false;
  54148. if (sphereCenter.z - sphereRadius > boxMax.z)
  54149. return false;
  54150. return true;
  54151. };
  54152. var getLowestRoot = (function () {
  54153. var result = { root: 0, found: false };
  54154. return function (a, b, c, maxR) {
  54155. result.root = 0;
  54156. result.found = false;
  54157. var determinant = b * b - 4.0 * a * c;
  54158. if (determinant < 0)
  54159. return result;
  54160. var sqrtD = Math.sqrt(determinant);
  54161. var r1 = (-b - sqrtD) / (2.0 * a);
  54162. var r2 = (-b + sqrtD) / (2.0 * a);
  54163. if (r1 > r2) {
  54164. var temp = r2;
  54165. r2 = r1;
  54166. r1 = temp;
  54167. }
  54168. if (r1 > 0 && r1 < maxR) {
  54169. result.root = r1;
  54170. result.found = true;
  54171. return result;
  54172. }
  54173. if (r2 > 0 && r2 < maxR) {
  54174. result.root = r2;
  54175. result.found = true;
  54176. return result;
  54177. }
  54178. return result;
  54179. };
  54180. })();
  54181. var Collider = /** @class */ (function () {
  54182. function Collider() {
  54183. this._collisionPoint = BABYLON.Vector3.Zero();
  54184. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54185. this._tempVector = BABYLON.Vector3.Zero();
  54186. this._tempVector2 = BABYLON.Vector3.Zero();
  54187. this._tempVector3 = BABYLON.Vector3.Zero();
  54188. this._tempVector4 = BABYLON.Vector3.Zero();
  54189. this._edge = BABYLON.Vector3.Zero();
  54190. this._baseToVertex = BABYLON.Vector3.Zero();
  54191. this._destinationPoint = BABYLON.Vector3.Zero();
  54192. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54193. this._displacementVector = BABYLON.Vector3.Zero();
  54194. this._radius = BABYLON.Vector3.One();
  54195. this._retry = 0;
  54196. this._basePointWorld = BABYLON.Vector3.Zero();
  54197. this._velocityWorld = BABYLON.Vector3.Zero();
  54198. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54199. this._collisionMask = -1;
  54200. }
  54201. Object.defineProperty(Collider.prototype, "collisionMask", {
  54202. get: function () {
  54203. return this._collisionMask;
  54204. },
  54205. set: function (mask) {
  54206. this._collisionMask = !isNaN(mask) ? mask : -1;
  54207. },
  54208. enumerable: true,
  54209. configurable: true
  54210. });
  54211. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54212. /**
  54213. * Gets the plane normal used to compute the sliding response (in local space)
  54214. */
  54215. get: function () {
  54216. return this._slidePlaneNormal;
  54217. },
  54218. enumerable: true,
  54219. configurable: true
  54220. });
  54221. // Methods
  54222. Collider.prototype._initialize = function (source, dir, e) {
  54223. this._velocity = dir;
  54224. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54225. this._basePoint = source;
  54226. source.multiplyToRef(this._radius, this._basePointWorld);
  54227. dir.multiplyToRef(this._radius, this._velocityWorld);
  54228. this._velocityWorldLength = this._velocityWorld.length();
  54229. this._epsilon = e;
  54230. this.collisionFound = false;
  54231. };
  54232. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54233. pa.subtractToRef(point, this._tempVector);
  54234. pb.subtractToRef(point, this._tempVector2);
  54235. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54236. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54237. if (d < 0)
  54238. return false;
  54239. pc.subtractToRef(point, this._tempVector3);
  54240. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54241. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54242. if (d < 0)
  54243. return false;
  54244. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54245. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54246. return d >= 0;
  54247. };
  54248. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54249. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54250. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54251. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54252. return false;
  54253. }
  54254. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54255. return false;
  54256. return true;
  54257. };
  54258. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54259. var t0;
  54260. var embeddedInPlane = false;
  54261. //defensive programming, actually not needed.
  54262. if (!trianglePlaneArray) {
  54263. trianglePlaneArray = [];
  54264. }
  54265. if (!trianglePlaneArray[faceIndex]) {
  54266. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54267. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54268. }
  54269. var trianglePlane = trianglePlaneArray[faceIndex];
  54270. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54271. return;
  54272. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54273. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54274. if (normalDotVelocity == 0) {
  54275. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54276. return;
  54277. embeddedInPlane = true;
  54278. t0 = 0;
  54279. }
  54280. else {
  54281. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54282. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54283. if (t0 > t1) {
  54284. var temp = t1;
  54285. t1 = t0;
  54286. t0 = temp;
  54287. }
  54288. if (t0 > 1.0 || t1 < 0.0)
  54289. return;
  54290. if (t0 < 0)
  54291. t0 = 0;
  54292. if (t0 > 1.0)
  54293. t0 = 1.0;
  54294. }
  54295. this._collisionPoint.copyFromFloats(0, 0, 0);
  54296. var found = false;
  54297. var t = 1.0;
  54298. if (!embeddedInPlane) {
  54299. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54300. this._velocity.scaleToRef(t0, this._tempVector);
  54301. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54302. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54303. found = true;
  54304. t = t0;
  54305. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54306. }
  54307. }
  54308. if (!found) {
  54309. var velocitySquaredLength = this._velocity.lengthSquared();
  54310. var a = velocitySquaredLength;
  54311. this._basePoint.subtractToRef(p1, this._tempVector);
  54312. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54313. var c = this._tempVector.lengthSquared() - 1.0;
  54314. var lowestRoot = getLowestRoot(a, b, c, t);
  54315. if (lowestRoot.found) {
  54316. t = lowestRoot.root;
  54317. found = true;
  54318. this._collisionPoint.copyFrom(p1);
  54319. }
  54320. this._basePoint.subtractToRef(p2, this._tempVector);
  54321. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54322. c = this._tempVector.lengthSquared() - 1.0;
  54323. lowestRoot = getLowestRoot(a, b, c, t);
  54324. if (lowestRoot.found) {
  54325. t = lowestRoot.root;
  54326. found = true;
  54327. this._collisionPoint.copyFrom(p2);
  54328. }
  54329. this._basePoint.subtractToRef(p3, this._tempVector);
  54330. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54331. c = this._tempVector.lengthSquared() - 1.0;
  54332. lowestRoot = getLowestRoot(a, b, c, t);
  54333. if (lowestRoot.found) {
  54334. t = lowestRoot.root;
  54335. found = true;
  54336. this._collisionPoint.copyFrom(p3);
  54337. }
  54338. p2.subtractToRef(p1, this._edge);
  54339. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54340. var edgeSquaredLength = this._edge.lengthSquared();
  54341. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54342. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54343. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54344. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54345. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54346. lowestRoot = getLowestRoot(a, b, c, t);
  54347. if (lowestRoot.found) {
  54348. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54349. if (f >= 0.0 && f <= 1.0) {
  54350. t = lowestRoot.root;
  54351. found = true;
  54352. this._edge.scaleInPlace(f);
  54353. p1.addToRef(this._edge, this._collisionPoint);
  54354. }
  54355. }
  54356. p3.subtractToRef(p2, this._edge);
  54357. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54358. edgeSquaredLength = this._edge.lengthSquared();
  54359. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54360. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54361. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54362. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54363. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54364. lowestRoot = getLowestRoot(a, b, c, t);
  54365. if (lowestRoot.found) {
  54366. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54367. if (f >= 0.0 && f <= 1.0) {
  54368. t = lowestRoot.root;
  54369. found = true;
  54370. this._edge.scaleInPlace(f);
  54371. p2.addToRef(this._edge, this._collisionPoint);
  54372. }
  54373. }
  54374. p1.subtractToRef(p3, this._edge);
  54375. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54376. edgeSquaredLength = this._edge.lengthSquared();
  54377. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54378. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54379. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54380. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54381. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54382. lowestRoot = getLowestRoot(a, b, c, t);
  54383. if (lowestRoot.found) {
  54384. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54385. if (f >= 0.0 && f <= 1.0) {
  54386. t = lowestRoot.root;
  54387. found = true;
  54388. this._edge.scaleInPlace(f);
  54389. p3.addToRef(this._edge, this._collisionPoint);
  54390. }
  54391. }
  54392. }
  54393. if (found) {
  54394. var distToCollision = t * this._velocity.length();
  54395. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54396. if (!this.intersectionPoint) {
  54397. this.intersectionPoint = this._collisionPoint.clone();
  54398. }
  54399. else {
  54400. this.intersectionPoint.copyFrom(this._collisionPoint);
  54401. }
  54402. this._nearestDistance = distToCollision;
  54403. this.collisionFound = true;
  54404. }
  54405. }
  54406. };
  54407. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54408. for (var i = indexStart; i < indexEnd; i += 3) {
  54409. var p1 = pts[indices[i] - decal];
  54410. var p2 = pts[indices[i + 1] - decal];
  54411. var p3 = pts[indices[i + 2] - decal];
  54412. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54413. }
  54414. };
  54415. Collider.prototype._getResponse = function (pos, vel) {
  54416. pos.addToRef(vel, this._destinationPoint);
  54417. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54418. this._basePoint.addToRef(vel, pos);
  54419. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54420. this._slidePlaneNormal.normalize();
  54421. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54422. pos.addInPlace(this._displacementVector);
  54423. this.intersectionPoint.addInPlace(this._displacementVector);
  54424. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54425. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54426. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54427. };
  54428. return Collider;
  54429. }());
  54430. BABYLON.Collider = Collider;
  54431. })(BABYLON || (BABYLON = {}));
  54432. //# sourceMappingURL=babylon.collider.js.map
  54433. var BABYLON;
  54434. (function (BABYLON) {
  54435. //WebWorker code will be inserted to this variable.
  54436. BABYLON.CollisionWorker = "";
  54437. /** Defines supported task for worker process */
  54438. var WorkerTaskType;
  54439. (function (WorkerTaskType) {
  54440. /** Initialization */
  54441. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54442. /** Update of geometry */
  54443. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54444. /** Evaluate collision */
  54445. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54446. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54447. /** Defines kind of replies returned by worker */
  54448. var WorkerReplyType;
  54449. (function (WorkerReplyType) {
  54450. /** Success */
  54451. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54452. /** Unkown error */
  54453. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54454. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54455. var CollisionCoordinatorWorker = /** @class */ (function () {
  54456. function CollisionCoordinatorWorker() {
  54457. var _this = this;
  54458. this._scaledPosition = BABYLON.Vector3.Zero();
  54459. this._scaledVelocity = BABYLON.Vector3.Zero();
  54460. this.onMeshUpdated = function (transformNode) {
  54461. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54462. };
  54463. this.onGeometryUpdated = function (geometry) {
  54464. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54465. };
  54466. this._afterRender = function () {
  54467. if (!_this._init)
  54468. return;
  54469. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54470. return;
  54471. }
  54472. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54473. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54474. if (_this._runningUpdated > 4) {
  54475. return;
  54476. }
  54477. ++_this._runningUpdated;
  54478. var payload = {
  54479. updatedMeshes: _this._addUpdateMeshesList,
  54480. updatedGeometries: _this._addUpdateGeometriesList,
  54481. removedGeometries: _this._toRemoveGeometryArray,
  54482. removedMeshes: _this._toRemoveMeshesArray
  54483. };
  54484. var message = {
  54485. payload: payload,
  54486. taskType: WorkerTaskType.UPDATE
  54487. };
  54488. var serializable = [];
  54489. for (var id in payload.updatedGeometries) {
  54490. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54491. //prepare transferables
  54492. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54493. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54494. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54495. }
  54496. }
  54497. _this._worker.postMessage(message, serializable);
  54498. _this._addUpdateMeshesList = {};
  54499. _this._addUpdateGeometriesList = {};
  54500. _this._toRemoveGeometryArray = [];
  54501. _this._toRemoveMeshesArray = [];
  54502. };
  54503. this._onMessageFromWorker = function (e) {
  54504. var returnData = e.data;
  54505. if (returnData.error != WorkerReplyType.SUCCESS) {
  54506. //TODO what errors can be returned from the worker?
  54507. BABYLON.Tools.Warn("error returned from worker!");
  54508. return;
  54509. }
  54510. switch (returnData.taskType) {
  54511. case WorkerTaskType.INIT:
  54512. _this._init = true;
  54513. //Update the worked with ALL of the scene's current state
  54514. _this._scene.meshes.forEach(function (mesh) {
  54515. _this.onMeshAdded(mesh);
  54516. });
  54517. _this._scene.getGeometries().forEach(function (geometry) {
  54518. _this.onGeometryAdded(geometry);
  54519. });
  54520. break;
  54521. case WorkerTaskType.UPDATE:
  54522. _this._runningUpdated--;
  54523. break;
  54524. case WorkerTaskType.COLLIDE:
  54525. var returnPayload = returnData.payload;
  54526. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54527. return;
  54528. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54529. if (callback) {
  54530. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54531. if (mesh) {
  54532. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54533. }
  54534. }
  54535. //cleanup
  54536. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54537. break;
  54538. }
  54539. };
  54540. this._collisionsCallbackArray = [];
  54541. this._init = false;
  54542. this._runningUpdated = 0;
  54543. this._addUpdateMeshesList = {};
  54544. this._addUpdateGeometriesList = {};
  54545. this._toRemoveGeometryArray = [];
  54546. this._toRemoveMeshesArray = [];
  54547. }
  54548. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54549. if (!this._init)
  54550. return;
  54551. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54552. return;
  54553. position.divideToRef(collider._radius, this._scaledPosition);
  54554. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54555. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54556. var payload = {
  54557. collider: {
  54558. position: this._scaledPosition.asArray(),
  54559. velocity: this._scaledVelocity.asArray(),
  54560. radius: collider._radius.asArray()
  54561. },
  54562. collisionId: collisionIndex,
  54563. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54564. maximumRetry: maximumRetry
  54565. };
  54566. var message = {
  54567. payload: payload,
  54568. taskType: WorkerTaskType.COLLIDE
  54569. };
  54570. this._worker.postMessage(message);
  54571. };
  54572. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54573. this._scene = scene;
  54574. this._scene.registerAfterRender(this._afterRender);
  54575. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54576. this._worker = new Worker(workerUrl);
  54577. this._worker.onmessage = this._onMessageFromWorker;
  54578. var message = {
  54579. payload: {},
  54580. taskType: WorkerTaskType.INIT
  54581. };
  54582. this._worker.postMessage(message);
  54583. };
  54584. CollisionCoordinatorWorker.prototype.destroy = function () {
  54585. this._scene.unregisterAfterRender(this._afterRender);
  54586. this._worker.terminate();
  54587. };
  54588. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54589. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54590. this.onMeshUpdated(mesh);
  54591. };
  54592. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54593. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54594. };
  54595. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54596. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54597. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54598. this.onGeometryUpdated(geometry);
  54599. };
  54600. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54601. this._toRemoveGeometryArray.push(geometry.id);
  54602. };
  54603. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54604. var submeshes = [];
  54605. if (mesh.subMeshes) {
  54606. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54607. var boundingInfo = sm.getBoundingInfo();
  54608. return {
  54609. position: idx,
  54610. verticesStart: sm.verticesStart,
  54611. verticesCount: sm.verticesCount,
  54612. indexStart: sm.indexStart,
  54613. indexCount: sm.indexCount,
  54614. hasMaterial: !!sm.getMaterial(),
  54615. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54616. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54617. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54618. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54619. };
  54620. });
  54621. }
  54622. var geometryId = null;
  54623. if (mesh instanceof BABYLON.Mesh) {
  54624. var geometry = mesh.geometry;
  54625. geometryId = geometry ? geometry.id : null;
  54626. }
  54627. else if (mesh instanceof BABYLON.InstancedMesh) {
  54628. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54629. geometryId = geometry ? geometry.id : null;
  54630. }
  54631. var boundingInfo = mesh.getBoundingInfo();
  54632. return {
  54633. uniqueId: mesh.uniqueId,
  54634. id: mesh.id,
  54635. name: mesh.name,
  54636. geometryId: geometryId,
  54637. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54638. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54639. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54640. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54641. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54642. subMeshes: submeshes,
  54643. checkCollisions: mesh.checkCollisions
  54644. };
  54645. };
  54646. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54647. return {
  54648. id: geometry.id,
  54649. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54650. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54651. indices: new Uint32Array(geometry.getIndices() || []),
  54652. };
  54653. };
  54654. return CollisionCoordinatorWorker;
  54655. }());
  54656. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54657. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54658. function CollisionCoordinatorLegacy() {
  54659. this._scaledPosition = BABYLON.Vector3.Zero();
  54660. this._scaledVelocity = BABYLON.Vector3.Zero();
  54661. this._finalPosition = BABYLON.Vector3.Zero();
  54662. }
  54663. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54664. position.divideToRef(collider._radius, this._scaledPosition);
  54665. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54666. collider.collidedMesh = null;
  54667. collider._retry = 0;
  54668. collider._initialVelocity = this._scaledVelocity;
  54669. collider._initialPosition = this._scaledPosition;
  54670. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54671. this._finalPosition.multiplyInPlace(collider._radius);
  54672. //run the callback
  54673. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54674. };
  54675. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54676. this._scene = scene;
  54677. };
  54678. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54679. //Legacy need no destruction method.
  54680. };
  54681. //No update in legacy mode
  54682. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54683. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54684. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54685. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54686. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54687. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54688. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54689. if (excludedMesh === void 0) { excludedMesh = null; }
  54690. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54691. if (collider._retry >= maximumRetry) {
  54692. finalPosition.copyFrom(position);
  54693. return;
  54694. }
  54695. // Check if this is a mesh else camera or -1
  54696. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54697. collider._initialize(position, velocity, closeDistance);
  54698. // Check all meshes
  54699. for (var index = 0; index < this._scene.meshes.length; index++) {
  54700. var mesh = this._scene.meshes[index];
  54701. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54702. mesh._checkCollision(collider);
  54703. }
  54704. }
  54705. if (!collider.collisionFound) {
  54706. position.addToRef(velocity, finalPosition);
  54707. return;
  54708. }
  54709. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54710. collider._getResponse(position, velocity);
  54711. }
  54712. if (velocity.length() <= closeDistance) {
  54713. finalPosition.copyFrom(position);
  54714. return;
  54715. }
  54716. collider._retry++;
  54717. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54718. };
  54719. return CollisionCoordinatorLegacy;
  54720. }());
  54721. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54722. })(BABYLON || (BABYLON = {}));
  54723. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54724. var BABYLON;
  54725. (function (BABYLON) {
  54726. /**
  54727. * A particle represents one of the element emitted by a particle system.
  54728. * This is mainly define by its coordinates, direction, velocity and age.
  54729. */
  54730. var Particle = /** @class */ (function () {
  54731. /**
  54732. * Creates a new instance Particle
  54733. * @param particleSystem the particle system the particle belongs to
  54734. */
  54735. function Particle(
  54736. /**
  54737. * particleSystem the particle system the particle belongs to.
  54738. */
  54739. particleSystem) {
  54740. this.particleSystem = particleSystem;
  54741. /**
  54742. * The world position of the particle in the scene.
  54743. */
  54744. this.position = BABYLON.Vector3.Zero();
  54745. /**
  54746. * The world direction of the particle in the scene.
  54747. */
  54748. this.direction = BABYLON.Vector3.Zero();
  54749. /**
  54750. * The color of the particle.
  54751. */
  54752. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54753. /**
  54754. * The color change of the particle per step.
  54755. */
  54756. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54757. /**
  54758. * Defines how long will the life of the particle be.
  54759. */
  54760. this.lifeTime = 1.0;
  54761. /**
  54762. * The current age of the particle.
  54763. */
  54764. this.age = 0;
  54765. /**
  54766. * The current size of the particle.
  54767. */
  54768. this.size = 0;
  54769. /**
  54770. * The current scale of the particle.
  54771. */
  54772. this.scale = new BABYLON.Vector2(1, 1);
  54773. /**
  54774. * The current angle of the particle.
  54775. */
  54776. this.angle = 0;
  54777. /**
  54778. * Defines how fast is the angle changing.
  54779. */
  54780. this.angularSpeed = 0;
  54781. /**
  54782. * Defines the cell index used by the particle to be rendered from a sprite.
  54783. */
  54784. this.cellIndex = 0;
  54785. /** @hidden */
  54786. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54787. /** @hidden */
  54788. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54789. /** @hidden */
  54790. this._currentSize1 = 0;
  54791. /** @hidden */
  54792. this._currentSize2 = 0;
  54793. /** @hidden */
  54794. this._currentAngularSpeed1 = 0;
  54795. /** @hidden */
  54796. this._currentAngularSpeed2 = 0;
  54797. /** @hidden */
  54798. this._currentVelocity1 = 0;
  54799. /** @hidden */
  54800. this._currentVelocity2 = 0;
  54801. if (!this.particleSystem.isAnimationSheetEnabled) {
  54802. return;
  54803. }
  54804. this.updateCellInfoFromSystem();
  54805. }
  54806. Particle.prototype.updateCellInfoFromSystem = function () {
  54807. this.cellIndex = this.particleSystem.startSpriteCellID;
  54808. };
  54809. /**
  54810. * Defines how the sprite cell index is updated for the particle
  54811. */
  54812. Particle.prototype.updateCellIndex = function () {
  54813. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54814. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54815. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54816. };
  54817. /**
  54818. * Copy the properties of particle to another one.
  54819. * @param other the particle to copy the information to.
  54820. */
  54821. Particle.prototype.copyTo = function (other) {
  54822. other.position.copyFrom(this.position);
  54823. if (this._initialDirection) {
  54824. if (other._initialDirection) {
  54825. other._initialDirection.copyFrom(this._initialDirection);
  54826. }
  54827. else {
  54828. other._initialDirection = this._initialDirection.clone();
  54829. }
  54830. }
  54831. else {
  54832. other._initialDirection = null;
  54833. }
  54834. other.direction.copyFrom(this.direction);
  54835. other.color.copyFrom(this.color);
  54836. other.colorStep.copyFrom(this.colorStep);
  54837. other.lifeTime = this.lifeTime;
  54838. other.age = this.age;
  54839. other.size = this.size;
  54840. other.scale.copyFrom(this.scale);
  54841. other.angle = this.angle;
  54842. other.angularSpeed = this.angularSpeed;
  54843. other.particleSystem = this.particleSystem;
  54844. other.cellIndex = this.cellIndex;
  54845. if (this._currentColorGradient) {
  54846. other._currentColorGradient = this._currentColorGradient;
  54847. other._currentColor1.copyFrom(this._currentColor1);
  54848. other._currentColor2.copyFrom(this._currentColor2);
  54849. }
  54850. if (this._currentSizeGradient) {
  54851. other._currentSizeGradient = this._currentSizeGradient;
  54852. other._currentSize1 = this._currentSize1;
  54853. other._currentSize2 = this._currentSize2;
  54854. }
  54855. if (this._currentAngularSpeedGradient) {
  54856. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54857. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54858. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54859. }
  54860. if (this._currentVelocityGradient) {
  54861. other._currentVelocityGradient = this._currentVelocityGradient;
  54862. other._currentVelocity1 = this._currentVelocity1;
  54863. other._currentVelocity2 = this._currentVelocity2;
  54864. }
  54865. if (this.particleSystem.isAnimationSheetEnabled) {
  54866. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54867. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54868. }
  54869. };
  54870. return Particle;
  54871. }());
  54872. BABYLON.Particle = Particle;
  54873. })(BABYLON || (BABYLON = {}));
  54874. //# sourceMappingURL=babylon.particle.js.map
  54875. var BABYLON;
  54876. (function (BABYLON) {
  54877. /**
  54878. * This represents a particle system in Babylon.
  54879. * 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.
  54880. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54881. * @example https://doc.babylonjs.com/babylon101/particles
  54882. */
  54883. var ParticleSystem = /** @class */ (function () {
  54884. /**
  54885. * Instantiates a particle system.
  54886. * 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.
  54887. * @param name The name of the particle system
  54888. * @param capacity The max number of particles alive at the same time
  54889. * @param scene The scene the particle system belongs to
  54890. * @param customEffect a custom effect used to change the way particles are rendered by default
  54891. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54892. * @param epsilon Offset used to render the particles
  54893. */
  54894. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54895. if (customEffect === void 0) { customEffect = null; }
  54896. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54897. if (epsilon === void 0) { epsilon = 0.01; }
  54898. var _this = this;
  54899. /**
  54900. * List of animations used by the particle system.
  54901. */
  54902. this.animations = [];
  54903. /**
  54904. * The rendering group used by the Particle system to chose when to render.
  54905. */
  54906. this.renderingGroupId = 0;
  54907. /**
  54908. * The emitter represents the Mesh or position we are attaching the particle system to.
  54909. */
  54910. this.emitter = null;
  54911. /**
  54912. * The maximum number of particles to emit per frame
  54913. */
  54914. this.emitRate = 10;
  54915. /**
  54916. * If you want to launch only a few particles at once, that can be done, as well.
  54917. */
  54918. this.manualEmitCount = -1;
  54919. /**
  54920. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54921. */
  54922. this.updateSpeed = 0.01;
  54923. /**
  54924. * The amount of time the particle system is running (depends of the overall update speed).
  54925. */
  54926. this.targetStopDuration = 0;
  54927. /**
  54928. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54929. */
  54930. this.disposeOnStop = false;
  54931. /**
  54932. * Minimum power of emitting particles.
  54933. */
  54934. this.minEmitPower = 1;
  54935. /**
  54936. * Maximum power of emitting particles.
  54937. */
  54938. this.maxEmitPower = 1;
  54939. /**
  54940. * Minimum life time of emitting particles.
  54941. */
  54942. this.minLifeTime = 1;
  54943. /**
  54944. * Maximum life time of emitting particles.
  54945. */
  54946. this.maxLifeTime = 1;
  54947. /**
  54948. * Minimum Size of emitting particles.
  54949. */
  54950. this.minSize = 1;
  54951. /**
  54952. * Maximum Size of emitting particles.
  54953. */
  54954. this.maxSize = 1;
  54955. /**
  54956. * Minimum scale of emitting particles on X axis.
  54957. */
  54958. this.minScaleX = 1;
  54959. /**
  54960. * Maximum scale of emitting particles on X axis.
  54961. */
  54962. this.maxScaleX = 1;
  54963. /**
  54964. * Minimum scale of emitting particles on Y axis.
  54965. */
  54966. this.minScaleY = 1;
  54967. /**
  54968. * Maximum scale of emitting particles on Y axis.
  54969. */
  54970. this.maxScaleY = 1;
  54971. /**
  54972. * Gets or sets the minimal initial rotation in radians.
  54973. */
  54974. this.minInitialRotation = 0;
  54975. /**
  54976. * Gets or sets the maximal initial rotation in radians.
  54977. */
  54978. this.maxInitialRotation = 0;
  54979. /**
  54980. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54981. */
  54982. this.minAngularSpeed = 0;
  54983. /**
  54984. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54985. */
  54986. this.maxAngularSpeed = 0;
  54987. /**
  54988. * The layer mask we are rendering the particles through.
  54989. */
  54990. this.layerMask = 0x0FFFFFFF;
  54991. /**
  54992. * This can help using your own shader to render the particle system.
  54993. * The according effect will be created
  54994. */
  54995. this.customShader = null;
  54996. /**
  54997. * By default particle system starts as soon as they are created. This prevents the
  54998. * automatic start to happen and let you decide when to start emitting particles.
  54999. */
  55000. this.preventAutoStart = false;
  55001. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55002. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55003. /**
  55004. * Callback triggered when the particle animation is ending.
  55005. */
  55006. this.onAnimationEnd = null;
  55007. /**
  55008. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55009. */
  55010. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55011. /**
  55012. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55013. * to override the particles.
  55014. */
  55015. this.forceDepthWrite = false;
  55016. /**
  55017. * You can use gravity if you want to give an orientation to your particles.
  55018. */
  55019. this.gravity = BABYLON.Vector3.Zero();
  55020. this._colorGradients = null;
  55021. this._sizeGradients = null;
  55022. this._lifeTimeGradients = null;
  55023. this._angularSpeedGradients = null;
  55024. this._velocityGradients = null;
  55025. /**
  55026. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55027. */
  55028. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55029. /**
  55030. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55031. */
  55032. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55033. /**
  55034. * Color the particle will have at the end of its lifetime
  55035. */
  55036. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55037. /**
  55038. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55039. */
  55040. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55041. /**
  55042. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55043. */
  55044. this.spriteCellChangeSpeed = 1;
  55045. /**
  55046. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55047. */
  55048. this.startSpriteCellID = 0;
  55049. /**
  55050. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55051. */
  55052. this.endSpriteCellID = 0;
  55053. /**
  55054. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55055. */
  55056. this.spriteCellWidth = 0;
  55057. /**
  55058. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55059. */
  55060. this.spriteCellHeight = 0;
  55061. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55062. this.preWarmCycles = 0;
  55063. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55064. this.preWarmStepOffset = 1;
  55065. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55066. this.translationPivot = new BABYLON.Vector2(0, 0);
  55067. /**
  55068. * An event triggered when the system is disposed
  55069. */
  55070. this.onDisposeObservable = new BABYLON.Observable();
  55071. /**
  55072. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55073. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55074. */
  55075. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55076. this._particles = new Array();
  55077. this._stockParticles = new Array();
  55078. this._newPartsExcess = 0;
  55079. this._vertexBuffers = {};
  55080. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55081. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55082. this._scaledDirection = BABYLON.Vector3.Zero();
  55083. this._scaledGravity = BABYLON.Vector3.Zero();
  55084. this._currentRenderId = -1;
  55085. this._useInstancing = false;
  55086. this._started = false;
  55087. this._stopped = false;
  55088. this._actualFrame = 0;
  55089. this._isBillboardBased = true;
  55090. // start of sub system methods
  55091. /**
  55092. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55093. * Its lifetime will start back at 0.
  55094. */
  55095. this.recycleParticle = function (particle) {
  55096. var lastParticle = _this._particles.pop();
  55097. if (lastParticle !== particle) {
  55098. lastParticle.copyTo(particle);
  55099. }
  55100. _this._stockParticles.push(lastParticle);
  55101. };
  55102. this._createParticle = function () {
  55103. var particle;
  55104. if (_this._stockParticles.length !== 0) {
  55105. particle = _this._stockParticles.pop();
  55106. particle.age = 0;
  55107. particle._currentColorGradient = null;
  55108. particle.cellIndex = _this.startSpriteCellID;
  55109. }
  55110. else {
  55111. particle = new BABYLON.Particle(_this);
  55112. }
  55113. return particle;
  55114. };
  55115. this._emitFromParticle = function (particle) {
  55116. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55117. return;
  55118. }
  55119. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55120. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55121. subSystem._rootParticleSystem = _this;
  55122. _this.activeSubSystems.push(subSystem);
  55123. subSystem.start();
  55124. };
  55125. this.id = name;
  55126. this.name = name;
  55127. this._capacity = capacity;
  55128. this._epsilon = epsilon;
  55129. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55130. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55131. this._customEffect = customEffect;
  55132. scene.particleSystems.push(this);
  55133. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55134. this._createIndexBuffer();
  55135. this._createVertexBuffers();
  55136. // Default emitter type
  55137. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55138. this.updateFunction = function (particles) {
  55139. var noiseTextureData = null;
  55140. var noiseTextureSize = null;
  55141. if (_this.noiseTexture) { // We need to get texture data back to CPU
  55142. noiseTextureData = (_this.noiseTexture.readPixels());
  55143. noiseTextureSize = _this.noiseTexture.getSize();
  55144. }
  55145. var _loop_1 = function () {
  55146. particle = particles[index];
  55147. particle.age += _this._scaledUpdateSpeed;
  55148. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55149. _this._emitFromParticle(particle);
  55150. _this.recycleParticle(particle);
  55151. index--;
  55152. return "continue";
  55153. }
  55154. else {
  55155. var ratio = particle.age / particle.lifeTime;
  55156. // Color
  55157. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55158. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55159. if (currentGradient !== particle._currentColorGradient) {
  55160. particle._currentColor1.copyFrom(particle._currentColor2);
  55161. nextGradient.getColorToRef(particle._currentColor2);
  55162. particle._currentColorGradient = currentGradient;
  55163. }
  55164. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55165. });
  55166. }
  55167. else {
  55168. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55169. particle.color.addInPlace(_this._scaledColorStep);
  55170. if (particle.color.a < 0) {
  55171. particle.color.a = 0;
  55172. }
  55173. }
  55174. // Angular speed
  55175. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55176. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55177. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55178. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55179. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55180. particle._currentAngularSpeedGradient = currentGradient;
  55181. }
  55182. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55183. });
  55184. }
  55185. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55186. // Direction
  55187. var directionScale_1 = _this._scaledUpdateSpeed;
  55188. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55189. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55190. if (currentGradient !== particle._currentVelocityGradient) {
  55191. particle._currentVelocity1 = particle._currentVelocity2;
  55192. particle._currentVelocity2 = nextGradient.getFactor();
  55193. particle._currentVelocityGradient = currentGradient;
  55194. }
  55195. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55196. });
  55197. }
  55198. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55199. particle.position.addInPlace(_this._scaledDirection);
  55200. // Noise
  55201. if (noiseTextureData && noiseTextureSize) {
  55202. var fetchedColorR = BABYLON.Tools.FetchR(particle.position.y, particle.position.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55203. var fetchedColorG = BABYLON.Tools.FetchR(particle.position.x + 0.33, particle.position.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55204. var fetchedColorB = BABYLON.Tools.FetchR(particle.position.x - 0.33, particle.position.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55205. var force = BABYLON.Tmp.Vector3[0];
  55206. var scaledForce = BABYLON.Tmp.Vector3[1];
  55207. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  55208. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  55209. particle.direction.addInPlace(scaledForce);
  55210. }
  55211. // Gravity
  55212. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55213. particle.direction.addInPlace(_this._scaledGravity);
  55214. // Size
  55215. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55216. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55217. if (currentGradient !== particle._currentSizeGradient) {
  55218. particle._currentSize1 = particle._currentSize2;
  55219. particle._currentSize2 = nextGradient.getFactor();
  55220. particle._currentSizeGradient = currentGradient;
  55221. }
  55222. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55223. });
  55224. }
  55225. if (_this._isAnimationSheetEnabled) {
  55226. particle.updateCellIndex();
  55227. }
  55228. }
  55229. };
  55230. var particle;
  55231. for (var index = 0; index < particles.length; index++) {
  55232. _loop_1();
  55233. }
  55234. };
  55235. }
  55236. /**
  55237. * Gets the current list of color gradients.
  55238. * You must use addColorGradient and removeColorGradient to udpate this list
  55239. * @returns the list of color gradients
  55240. */
  55241. ParticleSystem.prototype.getColorGradients = function () {
  55242. return this._colorGradients;
  55243. };
  55244. /**
  55245. * Gets the current list of size gradients.
  55246. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55247. * @returns the list of size gradients
  55248. */
  55249. ParticleSystem.prototype.getSizeGradients = function () {
  55250. return this._sizeGradients;
  55251. };
  55252. /**
  55253. * Gets the current list of life time gradients.
  55254. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55255. * @returns the list of life time gradients
  55256. */
  55257. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55258. return this._lifeTimeGradients;
  55259. };
  55260. /**
  55261. * Gets the current list of angular speed gradients.
  55262. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55263. * @returns the list of angular speed gradients
  55264. */
  55265. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55266. return this._angularSpeedGradients;
  55267. };
  55268. /**
  55269. * Gets the current list of velocity gradients.
  55270. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55271. * @returns the list of velocity gradients
  55272. */
  55273. ParticleSystem.prototype.getVelocityGradients = function () {
  55274. return this._velocityGradients;
  55275. };
  55276. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55277. /**
  55278. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55279. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55280. */
  55281. get: function () {
  55282. if (this.particleEmitterType.direction1) {
  55283. return this.particleEmitterType.direction1;
  55284. }
  55285. return BABYLON.Vector3.Zero();
  55286. },
  55287. set: function (value) {
  55288. if (this.particleEmitterType.direction1) {
  55289. this.particleEmitterType.direction1 = value;
  55290. }
  55291. },
  55292. enumerable: true,
  55293. configurable: true
  55294. });
  55295. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55296. /**
  55297. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55298. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55299. */
  55300. get: function () {
  55301. if (this.particleEmitterType.direction2) {
  55302. return this.particleEmitterType.direction2;
  55303. }
  55304. return BABYLON.Vector3.Zero();
  55305. },
  55306. set: function (value) {
  55307. if (this.particleEmitterType.direction2) {
  55308. this.particleEmitterType.direction2 = value;
  55309. }
  55310. },
  55311. enumerable: true,
  55312. configurable: true
  55313. });
  55314. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55315. /**
  55316. * 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.
  55317. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55318. */
  55319. get: function () {
  55320. if (this.particleEmitterType.minEmitBox) {
  55321. return this.particleEmitterType.minEmitBox;
  55322. }
  55323. return BABYLON.Vector3.Zero();
  55324. },
  55325. set: function (value) {
  55326. if (this.particleEmitterType.minEmitBox) {
  55327. this.particleEmitterType.minEmitBox = value;
  55328. }
  55329. },
  55330. enumerable: true,
  55331. configurable: true
  55332. });
  55333. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55334. /**
  55335. * 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.
  55336. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55337. */
  55338. get: function () {
  55339. if (this.particleEmitterType.maxEmitBox) {
  55340. return this.particleEmitterType.maxEmitBox;
  55341. }
  55342. return BABYLON.Vector3.Zero();
  55343. },
  55344. set: function (value) {
  55345. if (this.particleEmitterType.maxEmitBox) {
  55346. this.particleEmitterType.maxEmitBox = value;
  55347. }
  55348. },
  55349. enumerable: true,
  55350. configurable: true
  55351. });
  55352. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55353. /**
  55354. * Sets a callback that will be triggered when the system is disposed
  55355. */
  55356. set: function (callback) {
  55357. if (this._onDisposeObserver) {
  55358. this.onDisposeObservable.remove(this._onDisposeObserver);
  55359. }
  55360. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55361. },
  55362. enumerable: true,
  55363. configurable: true
  55364. });
  55365. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55366. /**
  55367. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55368. */
  55369. get: function () {
  55370. return this._isAnimationSheetEnabled;
  55371. },
  55372. enumerable: true,
  55373. configurable: true
  55374. });
  55375. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55376. /**
  55377. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55378. */
  55379. get: function () {
  55380. return this._isBillboardBased;
  55381. },
  55382. set: function (value) {
  55383. if (this._isBillboardBased === value) {
  55384. return;
  55385. }
  55386. this._isBillboardBased = value;
  55387. this._resetEffect();
  55388. },
  55389. enumerable: true,
  55390. configurable: true
  55391. });
  55392. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55393. //end of Sub-emitter
  55394. /**
  55395. * Gets the current list of active particles
  55396. */
  55397. get: function () {
  55398. return this._particles;
  55399. },
  55400. enumerable: true,
  55401. configurable: true
  55402. });
  55403. /**
  55404. * Returns the string "ParticleSystem"
  55405. * @returns a string containing the class name
  55406. */
  55407. ParticleSystem.prototype.getClassName = function () {
  55408. return "ParticleSystem";
  55409. };
  55410. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55411. var newGradient = new BABYLON.FactorGradient();
  55412. newGradient.gradient = gradient;
  55413. newGradient.factor1 = factor;
  55414. newGradient.factor2 = factor2;
  55415. factorGradients.push(newGradient);
  55416. factorGradients.sort(function (a, b) {
  55417. if (a.gradient < b.gradient) {
  55418. return -1;
  55419. }
  55420. else if (a.gradient > b.gradient) {
  55421. return 1;
  55422. }
  55423. return 0;
  55424. });
  55425. };
  55426. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55427. if (!factorGradients) {
  55428. return;
  55429. }
  55430. var index = 0;
  55431. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55432. var factorGradient = factorGradients_1[_i];
  55433. if (factorGradient.gradient === gradient) {
  55434. factorGradients.splice(index, 1);
  55435. break;
  55436. }
  55437. index++;
  55438. }
  55439. };
  55440. /**
  55441. * Adds a new life time gradient
  55442. * @param gradient defines the gradient to use (between 0 and 1)
  55443. * @param factor defines the life time factor to affect to the specified gradient
  55444. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55445. * @returns the current particle system
  55446. */
  55447. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55448. if (!this._lifeTimeGradients) {
  55449. this._lifeTimeGradients = [];
  55450. }
  55451. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55452. return this;
  55453. };
  55454. /**
  55455. * Remove a specific life time gradient
  55456. * @param gradient defines the gradient to remove
  55457. * @returns the current particle system
  55458. */
  55459. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55460. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55461. return this;
  55462. };
  55463. /**
  55464. * Adds a new size gradient
  55465. * @param gradient defines the gradient to use (between 0 and 1)
  55466. * @param factor defines the size factor to affect to the specified gradient
  55467. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55468. * @returns the current particle system
  55469. */
  55470. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55471. if (!this._sizeGradients) {
  55472. this._sizeGradients = [];
  55473. }
  55474. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55475. return this;
  55476. };
  55477. /**
  55478. * Remove a specific size gradient
  55479. * @param gradient defines the gradient to remove
  55480. * @returns the current particle system
  55481. */
  55482. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55483. this._removeFactorGradient(this._sizeGradients, gradient);
  55484. return this;
  55485. };
  55486. /**
  55487. * Adds a new angular speed gradient
  55488. * @param gradient defines the gradient to use (between 0 and 1)
  55489. * @param factor defines the size factor to affect to the specified gradient
  55490. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55491. * @returns the current particle system
  55492. */
  55493. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55494. if (!this._angularSpeedGradients) {
  55495. this._angularSpeedGradients = [];
  55496. }
  55497. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55498. return this;
  55499. };
  55500. /**
  55501. * Remove a specific angular speed gradient
  55502. * @param gradient defines the gradient to remove
  55503. * @returns the current particle system
  55504. */
  55505. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55506. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55507. return this;
  55508. };
  55509. /**
  55510. * Adds a new velocity gradient
  55511. * @param gradient defines the gradient to use (between 0 and 1)
  55512. * @param factor defines the size factor to affect to the specified gradient
  55513. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55514. * @returns the current particle system
  55515. */
  55516. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55517. if (!this._velocityGradients) {
  55518. this._velocityGradients = [];
  55519. }
  55520. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55521. return this;
  55522. };
  55523. /**
  55524. * Remove a specific velocity gradient
  55525. * @param gradient defines the gradient to remove
  55526. * @returns the current particle system
  55527. */
  55528. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55529. this._removeFactorGradient(this._velocityGradients, gradient);
  55530. return this;
  55531. };
  55532. /**
  55533. * Adds a new color gradient
  55534. * @param gradient defines the gradient to use (between 0 and 1)
  55535. * @param color defines the color to affect to the specified gradient
  55536. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55537. */
  55538. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55539. if (!this._colorGradients) {
  55540. this._colorGradients = [];
  55541. }
  55542. var colorGradient = new BABYLON.ColorGradient();
  55543. colorGradient.gradient = gradient;
  55544. colorGradient.color1 = color;
  55545. colorGradient.color2 = color2;
  55546. this._colorGradients.push(colorGradient);
  55547. this._colorGradients.sort(function (a, b) {
  55548. if (a.gradient < b.gradient) {
  55549. return -1;
  55550. }
  55551. else if (a.gradient > b.gradient) {
  55552. return 1;
  55553. }
  55554. return 0;
  55555. });
  55556. return this;
  55557. };
  55558. /**
  55559. * Remove a specific color gradient
  55560. * @param gradient defines the gradient to remove
  55561. */
  55562. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55563. if (!this._colorGradients) {
  55564. return this;
  55565. }
  55566. var index = 0;
  55567. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55568. var colorGradient = _a[_i];
  55569. if (colorGradient.gradient === gradient) {
  55570. this._colorGradients.splice(index, 1);
  55571. break;
  55572. }
  55573. index++;
  55574. }
  55575. return this;
  55576. };
  55577. ParticleSystem.prototype._resetEffect = function () {
  55578. if (this._vertexBuffer) {
  55579. this._vertexBuffer.dispose();
  55580. this._vertexBuffer = null;
  55581. }
  55582. if (this._spriteBuffer) {
  55583. this._spriteBuffer.dispose();
  55584. this._spriteBuffer = null;
  55585. }
  55586. this._createVertexBuffers();
  55587. };
  55588. ParticleSystem.prototype._createVertexBuffers = function () {
  55589. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55590. if (this._isAnimationSheetEnabled) {
  55591. this._vertexBufferSize += 1;
  55592. }
  55593. if (!this._isBillboardBased) {
  55594. this._vertexBufferSize += 3;
  55595. }
  55596. var engine = this._scene.getEngine();
  55597. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55598. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55599. var dataOffset = 0;
  55600. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55601. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55602. dataOffset += 3;
  55603. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55604. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55605. dataOffset += 4;
  55606. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55607. this._vertexBuffers["angle"] = options;
  55608. dataOffset += 1;
  55609. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55610. this._vertexBuffers["size"] = size;
  55611. dataOffset += 2;
  55612. if (this._isAnimationSheetEnabled) {
  55613. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55614. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55615. dataOffset += 1;
  55616. }
  55617. if (!this._isBillboardBased) {
  55618. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55619. this._vertexBuffers["direction"] = directionBuffer;
  55620. dataOffset += 3;
  55621. }
  55622. var offsets;
  55623. if (this._useInstancing) {
  55624. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55625. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55626. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55627. }
  55628. else {
  55629. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55630. dataOffset += 2;
  55631. }
  55632. this._vertexBuffers["offset"] = offsets;
  55633. };
  55634. ParticleSystem.prototype._createIndexBuffer = function () {
  55635. if (this._useInstancing) {
  55636. return;
  55637. }
  55638. var indices = [];
  55639. var index = 0;
  55640. for (var count = 0; count < this._capacity; count++) {
  55641. indices.push(index);
  55642. indices.push(index + 1);
  55643. indices.push(index + 2);
  55644. indices.push(index);
  55645. indices.push(index + 2);
  55646. indices.push(index + 3);
  55647. index += 4;
  55648. }
  55649. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55650. };
  55651. /**
  55652. * Gets the maximum number of particles active at the same time.
  55653. * @returns The max number of active particles.
  55654. */
  55655. ParticleSystem.prototype.getCapacity = function () {
  55656. return this._capacity;
  55657. };
  55658. /**
  55659. * Gets Wether there are still active particles in the system.
  55660. * @returns True if it is alive, otherwise false.
  55661. */
  55662. ParticleSystem.prototype.isAlive = function () {
  55663. return this._alive;
  55664. };
  55665. /**
  55666. * Gets Wether the system has been started.
  55667. * @returns True if it has been started, otherwise false.
  55668. */
  55669. ParticleSystem.prototype.isStarted = function () {
  55670. return this._started;
  55671. };
  55672. /**
  55673. * Starts the particle system and begins to emit
  55674. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  55675. */
  55676. ParticleSystem.prototype.start = function (delay) {
  55677. var _this = this;
  55678. if (delay === void 0) { delay = 0; }
  55679. if (delay) {
  55680. setTimeout(function () {
  55681. _this.start(0);
  55682. }, delay);
  55683. return;
  55684. }
  55685. this._started = true;
  55686. this._stopped = false;
  55687. this._actualFrame = 0;
  55688. if (this.subEmitters && this.subEmitters.length != 0) {
  55689. this.activeSubSystems = new Array();
  55690. }
  55691. if (this.preWarmCycles) {
  55692. for (var index = 0; index < this.preWarmCycles; index++) {
  55693. this.animate(true);
  55694. }
  55695. }
  55696. };
  55697. /**
  55698. * Stops the particle system.
  55699. * @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.
  55700. */
  55701. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55702. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55703. this._stopped = true;
  55704. if (stopSubEmitters) {
  55705. this._stopSubEmitters();
  55706. }
  55707. };
  55708. // animation sheet
  55709. /**
  55710. * Remove all active particles
  55711. */
  55712. ParticleSystem.prototype.reset = function () {
  55713. this._stockParticles = [];
  55714. this._particles = [];
  55715. };
  55716. /**
  55717. * @hidden (for internal use only)
  55718. */
  55719. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55720. var offset = index * this._vertexBufferSize;
  55721. this._vertexData[offset++] = particle.position.x;
  55722. this._vertexData[offset++] = particle.position.y;
  55723. this._vertexData[offset++] = particle.position.z;
  55724. this._vertexData[offset++] = particle.color.r;
  55725. this._vertexData[offset++] = particle.color.g;
  55726. this._vertexData[offset++] = particle.color.b;
  55727. this._vertexData[offset++] = particle.color.a;
  55728. this._vertexData[offset++] = particle.angle;
  55729. this._vertexData[offset++] = particle.scale.x * particle.size;
  55730. this._vertexData[offset++] = particle.scale.y * particle.size;
  55731. if (this._isAnimationSheetEnabled) {
  55732. this._vertexData[offset++] = particle.cellIndex;
  55733. }
  55734. if (!this._isBillboardBased) {
  55735. if (particle._initialDirection) {
  55736. this._vertexData[offset++] = particle._initialDirection.x;
  55737. this._vertexData[offset++] = particle._initialDirection.y;
  55738. this._vertexData[offset++] = particle._initialDirection.z;
  55739. }
  55740. else {
  55741. this._vertexData[offset++] = particle.direction.x;
  55742. this._vertexData[offset++] = particle.direction.y;
  55743. this._vertexData[offset++] = particle.direction.z;
  55744. }
  55745. }
  55746. if (!this._useInstancing) {
  55747. if (this._isAnimationSheetEnabled) {
  55748. if (offsetX === 0)
  55749. offsetX = this._epsilon;
  55750. else if (offsetX === 1)
  55751. offsetX = 1 - this._epsilon;
  55752. if (offsetY === 0)
  55753. offsetY = this._epsilon;
  55754. else if (offsetY === 1)
  55755. offsetY = 1 - this._epsilon;
  55756. }
  55757. this._vertexData[offset++] = offsetX;
  55758. this._vertexData[offset++] = offsetY;
  55759. }
  55760. };
  55761. ParticleSystem.prototype._stopSubEmitters = function () {
  55762. if (!this.activeSubSystems) {
  55763. return;
  55764. }
  55765. this.activeSubSystems.forEach(function (subSystem) {
  55766. subSystem.stop(true);
  55767. });
  55768. this.activeSubSystems = new Array();
  55769. };
  55770. ParticleSystem.prototype._removeFromRoot = function () {
  55771. if (!this._rootParticleSystem) {
  55772. return;
  55773. }
  55774. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55775. if (index !== -1) {
  55776. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55777. }
  55778. };
  55779. // End of sub system methods
  55780. ParticleSystem.prototype._update = function (newParticles) {
  55781. // Update current
  55782. this._alive = this._particles.length > 0;
  55783. this.updateFunction(this._particles);
  55784. // Add new ones
  55785. var worldMatrix;
  55786. if (this.emitter.position) {
  55787. var emitterMesh = this.emitter;
  55788. worldMatrix = emitterMesh.getWorldMatrix();
  55789. }
  55790. else {
  55791. var emitterPosition = this.emitter;
  55792. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55793. }
  55794. var particle;
  55795. var _loop_2 = function () {
  55796. if (this_1._particles.length === this_1._capacity) {
  55797. return "break";
  55798. }
  55799. particle = this_1._createParticle();
  55800. this_1._particles.push(particle);
  55801. // Emitter
  55802. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55803. if (this_1.startPositionFunction) {
  55804. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55805. }
  55806. else {
  55807. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55808. }
  55809. if (this_1.startDirectionFunction) {
  55810. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55811. }
  55812. else {
  55813. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55814. }
  55815. if (emitPower === 0) {
  55816. if (!particle._initialDirection) {
  55817. particle._initialDirection = particle.direction.clone();
  55818. }
  55819. else {
  55820. particle._initialDirection.copyFrom(particle.direction);
  55821. }
  55822. }
  55823. else {
  55824. particle._initialDirection = null;
  55825. }
  55826. particle.direction.scaleInPlace(emitPower);
  55827. // Life time
  55828. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55829. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55830. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55831. var factorGradient1 = currentGradient;
  55832. var factorGradient2 = nextGradient;
  55833. var lifeTime1 = factorGradient1.getFactor();
  55834. var lifeTime2 = factorGradient2.getFactor();
  55835. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55836. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55837. });
  55838. }
  55839. else {
  55840. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55841. }
  55842. // Size
  55843. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55844. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55845. }
  55846. else {
  55847. particle._currentSizeGradient = this_1._sizeGradients[0];
  55848. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55849. particle.size = particle._currentSize1;
  55850. if (this_1._sizeGradients.length > 1) {
  55851. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55852. }
  55853. else {
  55854. particle._currentSize2 = particle._currentSize1;
  55855. }
  55856. }
  55857. // Size and scale
  55858. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55859. // Angle
  55860. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55861. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55862. }
  55863. else {
  55864. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55865. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55866. particle._currentAngularSpeed1 = particle.angularSpeed;
  55867. if (this_1._angularSpeedGradients.length > 1) {
  55868. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55869. }
  55870. else {
  55871. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55872. }
  55873. }
  55874. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55875. // Velocity
  55876. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55877. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55878. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55879. if (this_1._velocityGradients.length > 1) {
  55880. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55881. }
  55882. else {
  55883. particle._currentVelocity2 = particle._currentVelocity1;
  55884. }
  55885. }
  55886. // Color
  55887. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55888. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55889. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55890. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55891. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55892. }
  55893. else {
  55894. particle._currentColorGradient = this_1._colorGradients[0];
  55895. particle._currentColorGradient.getColorToRef(particle.color);
  55896. particle._currentColor1.copyFrom(particle.color);
  55897. if (this_1._colorGradients.length > 1) {
  55898. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55899. }
  55900. else {
  55901. particle._currentColor2.copyFrom(particle.color);
  55902. }
  55903. }
  55904. // Sheet
  55905. if (this_1._isAnimationSheetEnabled) {
  55906. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55907. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55908. }
  55909. };
  55910. var this_1 = this, step;
  55911. for (var index = 0; index < newParticles; index++) {
  55912. var state_1 = _loop_2();
  55913. if (state_1 === "break")
  55914. break;
  55915. }
  55916. };
  55917. /** @hidden */
  55918. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55919. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55920. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55921. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55922. if (isAnimationSheetEnabled) {
  55923. attributeNamesOrOptions.push("cellIndex");
  55924. }
  55925. if (!isBillboardBased) {
  55926. attributeNamesOrOptions.push("direction");
  55927. }
  55928. return attributeNamesOrOptions;
  55929. };
  55930. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55931. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55932. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55933. if (isAnimationSheetEnabled) {
  55934. effectCreationOption.push("particlesInfos");
  55935. }
  55936. return effectCreationOption;
  55937. };
  55938. ParticleSystem.prototype._getEffect = function () {
  55939. if (this._customEffect) {
  55940. return this._customEffect;
  55941. }
  55942. ;
  55943. var defines = [];
  55944. if (this._scene.clipPlane) {
  55945. defines.push("#define CLIPPLANE");
  55946. }
  55947. if (this._isAnimationSheetEnabled) {
  55948. defines.push("#define ANIMATESHEET");
  55949. }
  55950. if (this._isBillboardBased) {
  55951. defines.push("#define BILLBOARD");
  55952. switch (this.billboardMode) {
  55953. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55954. defines.push("#define BILLBOARDY");
  55955. break;
  55956. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55957. default:
  55958. break;
  55959. }
  55960. }
  55961. // Effect
  55962. var join = defines.join("\n");
  55963. if (this._cachedDefines !== join) {
  55964. this._cachedDefines = join;
  55965. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55966. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55967. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55968. }
  55969. return this._effect;
  55970. };
  55971. /**
  55972. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55973. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55974. */
  55975. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55976. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55977. if (!this._started)
  55978. return;
  55979. if (!preWarmOnly) {
  55980. var effect = this._getEffect();
  55981. // Check
  55982. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55983. return;
  55984. if (this._currentRenderId === this._scene.getRenderId()) {
  55985. return;
  55986. }
  55987. this._currentRenderId = this._scene.getRenderId();
  55988. }
  55989. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55990. // determine the number of particles we need to create
  55991. var newParticles;
  55992. if (this.manualEmitCount > -1) {
  55993. newParticles = this.manualEmitCount;
  55994. this._newPartsExcess = 0;
  55995. this.manualEmitCount = 0;
  55996. }
  55997. else {
  55998. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55999. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56000. }
  56001. if (this._newPartsExcess > 1.0) {
  56002. newParticles += this._newPartsExcess >> 0;
  56003. this._newPartsExcess -= this._newPartsExcess >> 0;
  56004. }
  56005. this._alive = false;
  56006. if (!this._stopped) {
  56007. this._actualFrame += this._scaledUpdateSpeed;
  56008. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56009. this.stop();
  56010. }
  56011. else {
  56012. newParticles = 0;
  56013. }
  56014. this._update(newParticles);
  56015. // Stopped?
  56016. if (this._stopped) {
  56017. if (!this._alive) {
  56018. this._started = false;
  56019. if (this.onAnimationEnd) {
  56020. this.onAnimationEnd();
  56021. }
  56022. if (this.disposeOnStop) {
  56023. this._scene._toBeDisposed.push(this);
  56024. }
  56025. }
  56026. }
  56027. if (!preWarmOnly) {
  56028. // Update VBO
  56029. var offset = 0;
  56030. for (var index = 0; index < this._particles.length; index++) {
  56031. var particle = this._particles[index];
  56032. this._appendParticleVertices(offset, particle);
  56033. offset += this._useInstancing ? 1 : 4;
  56034. }
  56035. if (this._vertexBuffer) {
  56036. this._vertexBuffer.update(this._vertexData);
  56037. }
  56038. }
  56039. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56040. this.stop();
  56041. }
  56042. };
  56043. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56044. this._appendParticleVertex(offset++, particle, 0, 0);
  56045. if (!this._useInstancing) {
  56046. this._appendParticleVertex(offset++, particle, 1, 0);
  56047. this._appendParticleVertex(offset++, particle, 1, 1);
  56048. this._appendParticleVertex(offset++, particle, 0, 1);
  56049. }
  56050. };
  56051. /**
  56052. * Rebuilds the particle system.
  56053. */
  56054. ParticleSystem.prototype.rebuild = function () {
  56055. this._createIndexBuffer();
  56056. if (this._vertexBuffer) {
  56057. this._vertexBuffer._rebuild();
  56058. }
  56059. };
  56060. /**
  56061. * Is this system ready to be used/rendered
  56062. * @return true if the system is ready
  56063. */
  56064. ParticleSystem.prototype.isReady = function () {
  56065. var effect = this._getEffect();
  56066. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56067. return false;
  56068. }
  56069. return true;
  56070. };
  56071. /**
  56072. * Renders the particle system in its current state.
  56073. * @returns the current number of particles
  56074. */
  56075. ParticleSystem.prototype.render = function () {
  56076. var effect = this._getEffect();
  56077. // Check
  56078. if (!this.isReady() || !this._particles.length) {
  56079. return 0;
  56080. }
  56081. var engine = this._scene.getEngine();
  56082. // Render
  56083. engine.enableEffect(effect);
  56084. engine.setState(false);
  56085. var viewMatrix = this._scene.getViewMatrix();
  56086. effect.setTexture("diffuseSampler", this.particleTexture);
  56087. effect.setMatrix("view", viewMatrix);
  56088. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56089. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56090. var baseSize = this.particleTexture.getBaseSize();
  56091. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56092. }
  56093. effect.setVector2("translationPivot", this.translationPivot);
  56094. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56095. if (this._isBillboardBased) {
  56096. var camera = this._scene.activeCamera;
  56097. effect.setVector3("eyePosition", camera.globalPosition);
  56098. }
  56099. if (this._scene.clipPlane) {
  56100. var clipPlane = this._scene.clipPlane;
  56101. var invView = viewMatrix.clone();
  56102. invView.invert();
  56103. effect.setMatrix("invView", invView);
  56104. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56105. }
  56106. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56107. // Draw order
  56108. switch (this.blendMode) {
  56109. case ParticleSystem.BLENDMODE_ADD:
  56110. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56111. break;
  56112. case ParticleSystem.BLENDMODE_ONEONE:
  56113. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56114. break;
  56115. case ParticleSystem.BLENDMODE_STANDARD:
  56116. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56117. break;
  56118. }
  56119. if (this.forceDepthWrite) {
  56120. engine.setDepthWrite(true);
  56121. }
  56122. if (this._useInstancing) {
  56123. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56124. engine.unbindInstanceAttributes();
  56125. }
  56126. else {
  56127. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56128. }
  56129. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56130. return this._particles.length;
  56131. };
  56132. /**
  56133. * Disposes the particle system and free the associated resources
  56134. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56135. */
  56136. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56137. if (disposeTexture === void 0) { disposeTexture = true; }
  56138. if (this._vertexBuffer) {
  56139. this._vertexBuffer.dispose();
  56140. this._vertexBuffer = null;
  56141. }
  56142. if (this._spriteBuffer) {
  56143. this._spriteBuffer.dispose();
  56144. this._spriteBuffer = null;
  56145. }
  56146. if (this._indexBuffer) {
  56147. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56148. this._indexBuffer = null;
  56149. }
  56150. if (disposeTexture && this.particleTexture) {
  56151. this.particleTexture.dispose();
  56152. this.particleTexture = null;
  56153. }
  56154. if (disposeTexture && this.noiseTexture) {
  56155. this.noiseTexture.dispose();
  56156. this.noiseTexture = null;
  56157. }
  56158. this._removeFromRoot();
  56159. // Remove from scene
  56160. var index = this._scene.particleSystems.indexOf(this);
  56161. if (index > -1) {
  56162. this._scene.particleSystems.splice(index, 1);
  56163. }
  56164. // Callback
  56165. this.onDisposeObservable.notifyObservers(this);
  56166. this.onDisposeObservable.clear();
  56167. };
  56168. /**
  56169. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56170. * @param radius The radius of the sphere to emit from
  56171. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56172. * @returns the emitter
  56173. */
  56174. ParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56175. if (radius === void 0) { radius = 1; }
  56176. if (radiusRange === void 0) { radiusRange = 1; }
  56177. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56178. this.particleEmitterType = particleEmitter;
  56179. return particleEmitter;
  56180. };
  56181. /**
  56182. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56183. * @param radius The radius of the sphere to emit from
  56184. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56185. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56186. * @returns the emitter
  56187. */
  56188. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56189. if (radius === void 0) { radius = 1; }
  56190. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56191. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56192. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56193. this.particleEmitterType = particleEmitter;
  56194. return particleEmitter;
  56195. };
  56196. /**
  56197. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56198. * @param radius The radius of the cone to emit from
  56199. * @param angle The base angle of the cone
  56200. * @returns the emitter
  56201. */
  56202. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56203. if (radius === void 0) { radius = 1; }
  56204. if (angle === void 0) { angle = Math.PI / 4; }
  56205. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56206. this.particleEmitterType = particleEmitter;
  56207. return particleEmitter;
  56208. };
  56209. // 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.
  56210. /**
  56211. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56212. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56213. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56214. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56215. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56216. * @returns the emitter
  56217. */
  56218. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56219. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56220. this.particleEmitterType = particleEmitter;
  56221. this.direction1 = direction1;
  56222. this.direction2 = direction2;
  56223. this.minEmitBox = minEmitBox;
  56224. this.maxEmitBox = maxEmitBox;
  56225. return particleEmitter;
  56226. };
  56227. // Clone
  56228. /**
  56229. * Clones the particle system.
  56230. * @param name The name of the cloned object
  56231. * @param newEmitter The new emitter to use
  56232. * @returns the cloned particle system
  56233. */
  56234. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56235. var custom = null;
  56236. var program = null;
  56237. if (this.customShader != null) {
  56238. program = this.customShader;
  56239. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56240. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56241. }
  56242. else if (this._customEffect) {
  56243. custom = this._customEffect;
  56244. }
  56245. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56246. result.customShader = program;
  56247. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56248. if (newEmitter === undefined) {
  56249. newEmitter = this.emitter;
  56250. }
  56251. result.emitter = newEmitter;
  56252. if (this.particleTexture) {
  56253. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56254. }
  56255. if (!this.preventAutoStart) {
  56256. result.start();
  56257. }
  56258. return result;
  56259. };
  56260. /**
  56261. * Serializes the particle system to a JSON object.
  56262. * @returns the JSON object
  56263. */
  56264. ParticleSystem.prototype.serialize = function () {
  56265. var serializationObject = {};
  56266. ParticleSystem._Serialize(serializationObject, this);
  56267. serializationObject.textureMask = this.textureMask.asArray();
  56268. serializationObject.customShader = this.customShader;
  56269. serializationObject.preventAutoStart = this.preventAutoStart;
  56270. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56271. return serializationObject;
  56272. };
  56273. /** @hidden */
  56274. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56275. serializationObject.name = particleSystem.name;
  56276. serializationObject.id = particleSystem.id;
  56277. serializationObject.capacity = particleSystem.getCapacity();
  56278. // Emitter
  56279. if (particleSystem.emitter.position) {
  56280. var emitterMesh = particleSystem.emitter;
  56281. serializationObject.emitterId = emitterMesh.id;
  56282. }
  56283. else {
  56284. var emitterPosition = particleSystem.emitter;
  56285. serializationObject.emitter = emitterPosition.asArray();
  56286. }
  56287. // Emitter
  56288. if (particleSystem.particleEmitterType) {
  56289. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56290. }
  56291. if (particleSystem.particleTexture) {
  56292. serializationObject.textureName = particleSystem.particleTexture.name;
  56293. }
  56294. // Animations
  56295. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56296. // Particle system
  56297. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56298. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56299. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56300. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56301. serializationObject.minSize = particleSystem.minSize;
  56302. serializationObject.maxSize = particleSystem.maxSize;
  56303. serializationObject.minScaleX = particleSystem.minScaleX;
  56304. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56305. serializationObject.minScaleY = particleSystem.minScaleY;
  56306. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56307. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56308. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56309. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56310. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56311. serializationObject.emitRate = particleSystem.emitRate;
  56312. serializationObject.gravity = particleSystem.gravity.asArray();
  56313. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  56314. serializationObject.color1 = particleSystem.color1.asArray();
  56315. serializationObject.color2 = particleSystem.color2.asArray();
  56316. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56317. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56318. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56319. serializationObject.blendMode = particleSystem.blendMode;
  56320. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56321. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56322. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56323. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56324. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56325. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56326. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56327. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56328. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56329. var colorGradients = particleSystem.getColorGradients();
  56330. if (colorGradients) {
  56331. serializationObject.colorGradients = [];
  56332. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56333. var colorGradient = colorGradients_1[_i];
  56334. var serializedGradient = {
  56335. gradient: colorGradient.gradient,
  56336. color1: colorGradient.color1.asArray()
  56337. };
  56338. if (colorGradient.color2) {
  56339. serializedGradient.color2 = colorGradient.color2.asArray();
  56340. }
  56341. serializationObject.colorGradients.push(serializedGradient);
  56342. }
  56343. }
  56344. var sizeGradients = particleSystem.getSizeGradients();
  56345. if (sizeGradients) {
  56346. serializationObject.sizeGradients = [];
  56347. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56348. var sizeGradient = sizeGradients_1[_a];
  56349. var serializedGradient = {
  56350. gradient: sizeGradient.gradient,
  56351. factor1: sizeGradient.factor1
  56352. };
  56353. if (sizeGradient.factor2 !== undefined) {
  56354. serializedGradient.factor2 = sizeGradient.factor2;
  56355. }
  56356. serializationObject.sizeGradients.push(serializedGradient);
  56357. }
  56358. }
  56359. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56360. if (angularSpeedGradients) {
  56361. serializationObject.angularSpeedGradients = [];
  56362. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56363. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56364. var serializedGradient = {
  56365. gradient: angularSpeedGradient.gradient,
  56366. factor1: angularSpeedGradient.factor1
  56367. };
  56368. if (angularSpeedGradient.factor2 !== undefined) {
  56369. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56370. }
  56371. serializationObject.angularSpeedGradients.push(serializedGradient);
  56372. }
  56373. }
  56374. var velocityGradients = particleSystem.getVelocityGradients();
  56375. if (velocityGradients) {
  56376. serializationObject.velocityGradients = [];
  56377. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56378. var velocityGradient = velocityGradients_1[_c];
  56379. var serializedGradient = {
  56380. gradient: velocityGradient.gradient,
  56381. factor1: velocityGradient.factor1
  56382. };
  56383. if (velocityGradient.factor2 !== undefined) {
  56384. serializedGradient.factor2 = velocityGradient.factor2;
  56385. }
  56386. serializationObject.velocityGradients.push(serializedGradient);
  56387. }
  56388. }
  56389. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  56390. var noiseTexture = particleSystem.noiseTexture;
  56391. serializationObject.noiseTexture = noiseTexture.serialize();
  56392. }
  56393. };
  56394. /** @hidden */
  56395. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56396. // Texture
  56397. if (parsedParticleSystem.textureName) {
  56398. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56399. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56400. }
  56401. // Emitter
  56402. if (parsedParticleSystem.emitterId === undefined) {
  56403. particleSystem.emitter = BABYLON.Vector3.Zero();
  56404. }
  56405. else if (parsedParticleSystem.emitterId) {
  56406. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56407. }
  56408. else {
  56409. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56410. }
  56411. // Misc.
  56412. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56413. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56414. }
  56415. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56416. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56417. }
  56418. // Animations
  56419. if (parsedParticleSystem.animations) {
  56420. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56421. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56422. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56423. }
  56424. }
  56425. if (parsedParticleSystem.autoAnimate) {
  56426. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56427. }
  56428. // Particle system
  56429. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56430. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56431. particleSystem.minSize = parsedParticleSystem.minSize;
  56432. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56433. if (parsedParticleSystem.minScaleX) {
  56434. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56435. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56436. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56437. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56438. }
  56439. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56440. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56441. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56442. }
  56443. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56444. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56445. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56446. }
  56447. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56448. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56449. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56450. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56451. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56452. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56453. if (parsedParticleSystem.noiseStrength) {
  56454. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  56455. }
  56456. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56457. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56458. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56459. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56460. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56461. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56462. if (parsedParticleSystem.colorGradients) {
  56463. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56464. var colorGradient = _a[_i];
  56465. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56466. }
  56467. }
  56468. if (parsedParticleSystem.sizeGradients) {
  56469. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56470. var sizeGradient = _c[_b];
  56471. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56472. }
  56473. }
  56474. if (parsedParticleSystem.angularSpeedGradients) {
  56475. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56476. var angularSpeedGradient = _e[_d];
  56477. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56478. }
  56479. }
  56480. if (parsedParticleSystem.velocityGradients) {
  56481. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56482. var velocityGradient = _g[_f];
  56483. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56484. }
  56485. }
  56486. if (parsedParticleSystem.noiseTexture) {
  56487. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  56488. }
  56489. // Emitter
  56490. var emitterType;
  56491. if (parsedParticleSystem.particleEmitterType) {
  56492. switch (parsedParticleSystem.particleEmitterType.type) {
  56493. case "SphereParticleEmitter":
  56494. emitterType = new BABYLON.SphereParticleEmitter();
  56495. break;
  56496. case "SphereDirectedParticleEmitter":
  56497. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56498. break;
  56499. case "ConeEmitter":
  56500. case "ConeParticleEmitter":
  56501. emitterType = new BABYLON.ConeParticleEmitter();
  56502. break;
  56503. case "BoxEmitter":
  56504. case "BoxParticleEmitter":
  56505. default:
  56506. emitterType = new BABYLON.BoxParticleEmitter();
  56507. break;
  56508. }
  56509. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56510. }
  56511. else {
  56512. emitterType = new BABYLON.BoxParticleEmitter();
  56513. emitterType.parse(parsedParticleSystem);
  56514. }
  56515. particleSystem.particleEmitterType = emitterType;
  56516. // Animation sheet
  56517. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56518. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56519. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56520. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56521. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56522. };
  56523. /**
  56524. * Parses a JSON object to create a particle system.
  56525. * @param parsedParticleSystem The JSON object to parse
  56526. * @param scene The scene to create the particle system in
  56527. * @param rootUrl The root url to use to load external dependencies like texture
  56528. * @returns the Parsed particle system
  56529. */
  56530. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56531. var name = parsedParticleSystem.name;
  56532. var custom = null;
  56533. var program = null;
  56534. if (parsedParticleSystem.customShader) {
  56535. program = parsedParticleSystem.customShader;
  56536. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56537. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56538. }
  56539. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56540. particleSystem.customShader = program;
  56541. if (parsedParticleSystem.id) {
  56542. particleSystem.id = parsedParticleSystem.id;
  56543. }
  56544. // Auto start
  56545. if (parsedParticleSystem.preventAutoStart) {
  56546. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56547. }
  56548. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56549. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56550. if (!particleSystem.preventAutoStart) {
  56551. particleSystem.start();
  56552. }
  56553. return particleSystem;
  56554. };
  56555. /**
  56556. * Source color is added to the destination color without alpha affecting the result.
  56557. */
  56558. ParticleSystem.BLENDMODE_ONEONE = 0;
  56559. /**
  56560. * Blend current color and particle color using particle’s alpha.
  56561. */
  56562. ParticleSystem.BLENDMODE_STANDARD = 1;
  56563. /**
  56564. * Add current color and particle color multiplied by particle’s alpha.
  56565. */
  56566. ParticleSystem.BLENDMODE_ADD = 2;
  56567. return ParticleSystem;
  56568. }());
  56569. BABYLON.ParticleSystem = ParticleSystem;
  56570. })(BABYLON || (BABYLON = {}));
  56571. //# sourceMappingURL=babylon.particleSystem.js.map
  56572. var BABYLON;
  56573. (function (BABYLON) {
  56574. /**
  56575. * Particle emitter emitting particles from the inside of a box.
  56576. * It emits the particles randomly between 2 given directions.
  56577. */
  56578. var BoxParticleEmitter = /** @class */ (function () {
  56579. /**
  56580. * Creates a new instance BoxParticleEmitter
  56581. */
  56582. function BoxParticleEmitter() {
  56583. /**
  56584. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56585. */
  56586. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56587. /**
  56588. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56589. */
  56590. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56591. /**
  56592. * 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.
  56593. */
  56594. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56595. /**
  56596. * 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.
  56597. */
  56598. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56599. }
  56600. /**
  56601. * Called by the particle System when the direction is computed for the created particle.
  56602. * @param worldMatrix is the world matrix of the particle system
  56603. * @param directionToUpdate is the direction vector to update with the result
  56604. * @param particle is the particle we are computed the direction for
  56605. */
  56606. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56607. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56608. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56609. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56610. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56611. };
  56612. /**
  56613. * Called by the particle System when the position is computed for the created particle.
  56614. * @param worldMatrix is the world matrix of the particle system
  56615. * @param positionToUpdate is the position vector to update with the result
  56616. * @param particle is the particle we are computed the position for
  56617. */
  56618. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56619. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56620. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56621. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56622. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56623. };
  56624. /**
  56625. * Clones the current emitter and returns a copy of it
  56626. * @returns the new emitter
  56627. */
  56628. BoxParticleEmitter.prototype.clone = function () {
  56629. var newOne = new BoxParticleEmitter();
  56630. BABYLON.Tools.DeepCopy(this, newOne);
  56631. return newOne;
  56632. };
  56633. /**
  56634. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56635. * @param effect defines the update shader
  56636. */
  56637. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56638. effect.setVector3("direction1", this.direction1);
  56639. effect.setVector3("direction2", this.direction2);
  56640. effect.setVector3("minEmitBox", this.minEmitBox);
  56641. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56642. };
  56643. /**
  56644. * Returns a string to use to update the GPU particles update shader
  56645. * @returns a string containng the defines string
  56646. */
  56647. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56648. return "#define BOXEMITTER";
  56649. };
  56650. /**
  56651. * Returns the string "BoxParticleEmitter"
  56652. * @returns a string containing the class name
  56653. */
  56654. BoxParticleEmitter.prototype.getClassName = function () {
  56655. return "BoxParticleEmitter";
  56656. };
  56657. /**
  56658. * Serializes the particle system to a JSON object.
  56659. * @returns the JSON object
  56660. */
  56661. BoxParticleEmitter.prototype.serialize = function () {
  56662. var serializationObject = {};
  56663. serializationObject.type = this.getClassName();
  56664. serializationObject.direction1 = this.direction1.asArray();
  56665. serializationObject.direction2 = this.direction2.asArray();
  56666. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56667. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56668. return serializationObject;
  56669. };
  56670. /**
  56671. * Parse properties from a JSON object
  56672. * @param serializationObject defines the JSON object
  56673. */
  56674. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56675. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56676. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56677. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56678. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56679. };
  56680. return BoxParticleEmitter;
  56681. }());
  56682. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56683. })(BABYLON || (BABYLON = {}));
  56684. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56685. var BABYLON;
  56686. (function (BABYLON) {
  56687. /**
  56688. * Particle emitter emitting particles from the inside of a cone.
  56689. * It emits the particles alongside the cone volume from the base to the particle.
  56690. * The emission direction might be randomized.
  56691. */
  56692. var ConeParticleEmitter = /** @class */ (function () {
  56693. /**
  56694. * Creates a new instance ConeParticleEmitter
  56695. * @param radius the radius of the emission cone (1 by default)
  56696. * @param angles the cone base angle (PI by default)
  56697. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56698. */
  56699. function ConeParticleEmitter(radius, angle,
  56700. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56701. directionRandomizer) {
  56702. if (radius === void 0) { radius = 1; }
  56703. if (angle === void 0) { angle = Math.PI; }
  56704. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56705. this.directionRandomizer = directionRandomizer;
  56706. /**
  56707. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56708. */
  56709. this.radiusRange = 1;
  56710. /**
  56711. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56712. */
  56713. this.heightRange = 1;
  56714. this.angle = angle;
  56715. this.radius = radius;
  56716. }
  56717. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56718. /**
  56719. * Gets or sets the radius of the emission cone
  56720. */
  56721. get: function () {
  56722. return this._radius;
  56723. },
  56724. set: function (value) {
  56725. this._radius = value;
  56726. this._buildHeight();
  56727. },
  56728. enumerable: true,
  56729. configurable: true
  56730. });
  56731. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56732. /**
  56733. * Gets or sets the angle of the emission cone
  56734. */
  56735. get: function () {
  56736. return this._angle;
  56737. },
  56738. set: function (value) {
  56739. this._angle = value;
  56740. this._buildHeight();
  56741. },
  56742. enumerable: true,
  56743. configurable: true
  56744. });
  56745. ConeParticleEmitter.prototype._buildHeight = function () {
  56746. if (this._angle !== 0) {
  56747. this._height = this._radius / Math.tan(this._angle / 2);
  56748. }
  56749. else {
  56750. this._height = 1;
  56751. }
  56752. };
  56753. /**
  56754. * Called by the particle System when the direction is computed for the created particle.
  56755. * @param worldMatrix is the world matrix of the particle system
  56756. * @param directionToUpdate is the direction vector to update with the result
  56757. * @param particle is the particle we are computed the direction for
  56758. */
  56759. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56760. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56761. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56762. }
  56763. else {
  56764. // measure the direction Vector from the emitter to the particle.
  56765. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56766. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56767. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56768. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56769. direction.x += randX;
  56770. direction.y += randY;
  56771. direction.z += randZ;
  56772. direction.normalize();
  56773. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56774. }
  56775. };
  56776. /**
  56777. * Called by the particle System when the position is computed for the created particle.
  56778. * @param worldMatrix is the world matrix of the particle system
  56779. * @param positionToUpdate is the position vector to update with the result
  56780. * @param particle is the particle we are computed the position for
  56781. */
  56782. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56783. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56784. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56785. // Better distribution in a cone at normal angles.
  56786. h = 1 - h * h;
  56787. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56788. radius = radius * h;
  56789. var randX = radius * Math.sin(s);
  56790. var randZ = radius * Math.cos(s);
  56791. var randY = h * this._height;
  56792. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56793. };
  56794. /**
  56795. * Clones the current emitter and returns a copy of it
  56796. * @returns the new emitter
  56797. */
  56798. ConeParticleEmitter.prototype.clone = function () {
  56799. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56800. BABYLON.Tools.DeepCopy(this, newOne);
  56801. return newOne;
  56802. };
  56803. /**
  56804. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56805. * @param effect defines the update shader
  56806. */
  56807. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56808. effect.setFloat2("radius", this._radius, this.radiusRange);
  56809. effect.setFloat("coneAngle", this._angle);
  56810. effect.setFloat2("height", this._height, this.heightRange);
  56811. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56812. };
  56813. /**
  56814. * Returns a string to use to update the GPU particles update shader
  56815. * @returns a string containng the defines string
  56816. */
  56817. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56818. return "#define CONEEMITTER";
  56819. };
  56820. /**
  56821. * Returns the string "ConeParticleEmitter"
  56822. * @returns a string containing the class name
  56823. */
  56824. ConeParticleEmitter.prototype.getClassName = function () {
  56825. return "ConeParticleEmitter";
  56826. };
  56827. /**
  56828. * Serializes the particle system to a JSON object.
  56829. * @returns the JSON object
  56830. */
  56831. ConeParticleEmitter.prototype.serialize = function () {
  56832. var serializationObject = {};
  56833. serializationObject.type = this.getClassName();
  56834. serializationObject.radius = this._radius;
  56835. serializationObject.angle = this._angle;
  56836. serializationObject.directionRandomizer = this.directionRandomizer;
  56837. return serializationObject;
  56838. };
  56839. /**
  56840. * Parse properties from a JSON object
  56841. * @param serializationObject defines the JSON object
  56842. */
  56843. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56844. this.radius = serializationObject.radius;
  56845. this.angle = serializationObject.angle;
  56846. this.directionRandomizer = serializationObject.directionRandomizer;
  56847. };
  56848. return ConeParticleEmitter;
  56849. }());
  56850. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56851. })(BABYLON || (BABYLON = {}));
  56852. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56853. var BABYLON;
  56854. (function (BABYLON) {
  56855. /**
  56856. * Particle emitter emitting particles from the inside of a sphere.
  56857. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56858. */
  56859. var SphereParticleEmitter = /** @class */ (function () {
  56860. /**
  56861. * Creates a new instance SphereParticleEmitter
  56862. * @param radius the radius of the emission sphere (1 by default)
  56863. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56864. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56865. */
  56866. function SphereParticleEmitter(
  56867. /**
  56868. * The radius of the emission sphere.
  56869. */
  56870. radius,
  56871. /**
  56872. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  56873. */
  56874. radiusRange,
  56875. /**
  56876. * How much to randomize the particle direction [0-1].
  56877. */
  56878. directionRandomizer) {
  56879. if (radius === void 0) { radius = 1; }
  56880. if (radiusRange === void 0) { radiusRange = 1; }
  56881. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56882. this.radius = radius;
  56883. this.radiusRange = radiusRange;
  56884. this.directionRandomizer = directionRandomizer;
  56885. }
  56886. /**
  56887. * Called by the particle System when the direction is computed for the created particle.
  56888. * @param worldMatrix is the world matrix of the particle system
  56889. * @param directionToUpdate is the direction vector to update with the result
  56890. * @param particle is the particle we are computed the direction for
  56891. */
  56892. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56893. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56894. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56895. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56896. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56897. direction.x += randX;
  56898. direction.y += randY;
  56899. direction.z += randZ;
  56900. direction.normalize();
  56901. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56902. };
  56903. /**
  56904. * Called by the particle System when the position is computed for the created particle.
  56905. * @param worldMatrix is the world matrix of the particle system
  56906. * @param positionToUpdate is the position vector to update with the result
  56907. * @param particle is the particle we are computed the position for
  56908. */
  56909. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56910. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56911. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56912. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56913. var theta = Math.acos(2 * v - 1);
  56914. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56915. var randY = randRadius * Math.cos(theta);
  56916. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56917. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56918. };
  56919. /**
  56920. * Clones the current emitter and returns a copy of it
  56921. * @returns the new emitter
  56922. */
  56923. SphereParticleEmitter.prototype.clone = function () {
  56924. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56925. BABYLON.Tools.DeepCopy(this, newOne);
  56926. return newOne;
  56927. };
  56928. /**
  56929. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56930. * @param effect defines the update shader
  56931. */
  56932. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56933. effect.setFloat("radius", this.radius);
  56934. effect.setFloat("radiusRange", this.radiusRange);
  56935. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56936. };
  56937. /**
  56938. * Returns a string to use to update the GPU particles update shader
  56939. * @returns a string containng the defines string
  56940. */
  56941. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56942. return "#define SPHEREEMITTER";
  56943. };
  56944. /**
  56945. * Returns the string "SphereParticleEmitter"
  56946. * @returns a string containing the class name
  56947. */
  56948. SphereParticleEmitter.prototype.getClassName = function () {
  56949. return "SphereParticleEmitter";
  56950. };
  56951. /**
  56952. * Serializes the particle system to a JSON object.
  56953. * @returns the JSON object
  56954. */
  56955. SphereParticleEmitter.prototype.serialize = function () {
  56956. var serializationObject = {};
  56957. serializationObject.type = this.getClassName();
  56958. serializationObject.radius = this.radius;
  56959. serializationObject.radiusRange = this.radiusRange;
  56960. serializationObject.directionRandomizer = this.directionRandomizer;
  56961. return serializationObject;
  56962. };
  56963. /**
  56964. * Parse properties from a JSON object
  56965. * @param serializationObject defines the JSON object
  56966. */
  56967. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56968. this.radius = serializationObject.radius;
  56969. this.radiusRange = serializationObject.radiusRange;
  56970. this.directionRandomizer = serializationObject.directionRandomizer;
  56971. };
  56972. return SphereParticleEmitter;
  56973. }());
  56974. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56975. /**
  56976. * Particle emitter emitting particles from the inside of a sphere.
  56977. * It emits the particles randomly between two vectors.
  56978. */
  56979. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56980. __extends(SphereDirectedParticleEmitter, _super);
  56981. /**
  56982. * Creates a new instance SphereDirectedParticleEmitter
  56983. * @param radius the radius of the emission sphere (1 by default)
  56984. * @param direction1 the min limit of the emission direction (up vector by default)
  56985. * @param direction2 the max limit of the emission direction (up vector by default)
  56986. */
  56987. function SphereDirectedParticleEmitter(radius,
  56988. /**
  56989. * The min limit of the emission direction.
  56990. */
  56991. direction1,
  56992. /**
  56993. * The max limit of the emission direction.
  56994. */
  56995. direction2) {
  56996. if (radius === void 0) { radius = 1; }
  56997. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56998. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56999. var _this = _super.call(this, radius) || this;
  57000. _this.direction1 = direction1;
  57001. _this.direction2 = direction2;
  57002. return _this;
  57003. }
  57004. /**
  57005. * Called by the particle System when the direction is computed for the created particle.
  57006. * @param worldMatrix is the world matrix of the particle system
  57007. * @param directionToUpdate is the direction vector to update with the result
  57008. * @param particle is the particle we are computed the direction for
  57009. */
  57010. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57011. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57012. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57013. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57014. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57015. };
  57016. /**
  57017. * Clones the current emitter and returns a copy of it
  57018. * @returns the new emitter
  57019. */
  57020. SphereDirectedParticleEmitter.prototype.clone = function () {
  57021. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57022. BABYLON.Tools.DeepCopy(this, newOne);
  57023. return newOne;
  57024. };
  57025. /**
  57026. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57027. * @param effect defines the update shader
  57028. */
  57029. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57030. effect.setFloat("radius", this.radius);
  57031. effect.setFloat("radiusRange", this.radiusRange);
  57032. effect.setVector3("direction1", this.direction1);
  57033. effect.setVector3("direction2", this.direction2);
  57034. };
  57035. /**
  57036. * Returns a string to use to update the GPU particles update shader
  57037. * @returns a string containng the defines string
  57038. */
  57039. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57040. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57041. };
  57042. /**
  57043. * Returns the string "SphereDirectedParticleEmitter"
  57044. * @returns a string containing the class name
  57045. */
  57046. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57047. return "SphereDirectedParticleEmitter";
  57048. };
  57049. /**
  57050. * Serializes the particle system to a JSON object.
  57051. * @returns the JSON object
  57052. */
  57053. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57054. var serializationObject = _super.prototype.serialize.call(this);
  57055. serializationObject.direction1 = this.direction1.asArray();
  57056. serializationObject.direction2 = this.direction2.asArray();
  57057. return serializationObject;
  57058. };
  57059. /**
  57060. * Parse properties from a JSON object
  57061. * @param serializationObject defines the JSON object
  57062. */
  57063. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57064. _super.prototype.parse.call(this, serializationObject);
  57065. this.direction1.copyFrom(serializationObject.direction1);
  57066. this.direction2.copyFrom(serializationObject.direction2);
  57067. };
  57068. return SphereDirectedParticleEmitter;
  57069. }(SphereParticleEmitter));
  57070. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57071. })(BABYLON || (BABYLON = {}));
  57072. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57073. var BABYLON;
  57074. (function (BABYLON) {
  57075. // Adds the parsers to the scene parsers.
  57076. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57077. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57078. if (!individualParser) {
  57079. return;
  57080. }
  57081. // Particles Systems
  57082. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57083. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57084. var parsedParticleSystem = parsedData.particleSystems[index];
  57085. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57086. }
  57087. }
  57088. });
  57089. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57090. if (parsedParticleSystem.activeParticleCount) {
  57091. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57092. return ps;
  57093. }
  57094. else {
  57095. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57096. return ps;
  57097. }
  57098. });
  57099. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57100. if (uniformsNames === void 0) { uniformsNames = []; }
  57101. if (samplers === void 0) { samplers = []; }
  57102. if (defines === void 0) { defines = ""; }
  57103. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57104. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57105. if (defines.indexOf(" BILLBOARD") === -1) {
  57106. defines += "\n#define BILLBOARD\n";
  57107. }
  57108. if (samplers.indexOf("diffuseSampler") === -1) {
  57109. samplers.push("diffuseSampler");
  57110. }
  57111. return this.createEffect({
  57112. vertex: "particles",
  57113. fragmentElement: fragmentName
  57114. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57115. };
  57116. })(BABYLON || (BABYLON = {}));
  57117. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57118. var BABYLON;
  57119. (function (BABYLON) {
  57120. var ShaderMaterial = /** @class */ (function (_super) {
  57121. __extends(ShaderMaterial, _super);
  57122. function ShaderMaterial(name, scene, shaderPath, options) {
  57123. var _this = _super.call(this, name, scene) || this;
  57124. _this._textures = {};
  57125. _this._textureArrays = {};
  57126. _this._floats = {};
  57127. _this._ints = {};
  57128. _this._floatsArrays = {};
  57129. _this._colors3 = {};
  57130. _this._colors3Arrays = {};
  57131. _this._colors4 = {};
  57132. _this._vectors2 = {};
  57133. _this._vectors3 = {};
  57134. _this._vectors4 = {};
  57135. _this._matrices = {};
  57136. _this._matrices3x3 = {};
  57137. _this._matrices2x2 = {};
  57138. _this._vectors2Arrays = {};
  57139. _this._vectors3Arrays = {};
  57140. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57141. _this._shaderPath = shaderPath;
  57142. options.needAlphaBlending = options.needAlphaBlending || false;
  57143. options.needAlphaTesting = options.needAlphaTesting || false;
  57144. options.attributes = options.attributes || ["position", "normal", "uv"];
  57145. options.uniforms = options.uniforms || ["worldViewProjection"];
  57146. options.uniformBuffers = options.uniformBuffers || [];
  57147. options.samplers = options.samplers || [];
  57148. options.defines = options.defines || [];
  57149. _this._options = options;
  57150. return _this;
  57151. }
  57152. ShaderMaterial.prototype.getClassName = function () {
  57153. return "ShaderMaterial";
  57154. };
  57155. ShaderMaterial.prototype.needAlphaBlending = function () {
  57156. return this._options.needAlphaBlending;
  57157. };
  57158. ShaderMaterial.prototype.needAlphaTesting = function () {
  57159. return this._options.needAlphaTesting;
  57160. };
  57161. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57162. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57163. this._options.uniforms.push(uniformName);
  57164. }
  57165. };
  57166. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57167. if (this._options.samplers.indexOf(name) === -1) {
  57168. this._options.samplers.push(name);
  57169. }
  57170. this._textures[name] = texture;
  57171. return this;
  57172. };
  57173. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57174. if (this._options.samplers.indexOf(name) === -1) {
  57175. this._options.samplers.push(name);
  57176. }
  57177. this._checkUniform(name);
  57178. this._textureArrays[name] = textures;
  57179. return this;
  57180. };
  57181. ShaderMaterial.prototype.setFloat = function (name, value) {
  57182. this._checkUniform(name);
  57183. this._floats[name] = value;
  57184. return this;
  57185. };
  57186. ShaderMaterial.prototype.setInt = function (name, value) {
  57187. this._checkUniform(name);
  57188. this._ints[name] = value;
  57189. return this;
  57190. };
  57191. ShaderMaterial.prototype.setFloats = function (name, value) {
  57192. this._checkUniform(name);
  57193. this._floatsArrays[name] = value;
  57194. return this;
  57195. };
  57196. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57197. this._checkUniform(name);
  57198. this._colors3[name] = value;
  57199. return this;
  57200. };
  57201. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57202. this._checkUniform(name);
  57203. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57204. color.toArray(arr, arr.length);
  57205. return arr;
  57206. }, []);
  57207. return this;
  57208. };
  57209. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57210. this._checkUniform(name);
  57211. this._colors4[name] = value;
  57212. return this;
  57213. };
  57214. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57215. this._checkUniform(name);
  57216. this._vectors2[name] = value;
  57217. return this;
  57218. };
  57219. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57220. this._checkUniform(name);
  57221. this._vectors3[name] = value;
  57222. return this;
  57223. };
  57224. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57225. this._checkUniform(name);
  57226. this._vectors4[name] = value;
  57227. return this;
  57228. };
  57229. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57230. this._checkUniform(name);
  57231. this._matrices[name] = value;
  57232. return this;
  57233. };
  57234. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57235. this._checkUniform(name);
  57236. this._matrices3x3[name] = value;
  57237. return this;
  57238. };
  57239. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57240. this._checkUniform(name);
  57241. this._matrices2x2[name] = value;
  57242. return this;
  57243. };
  57244. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57245. this._checkUniform(name);
  57246. this._vectors2Arrays[name] = value;
  57247. return this;
  57248. };
  57249. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57250. this._checkUniform(name);
  57251. this._vectors3Arrays[name] = value;
  57252. return this;
  57253. };
  57254. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57255. if (!mesh) {
  57256. return true;
  57257. }
  57258. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57259. return false;
  57260. }
  57261. return false;
  57262. };
  57263. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57264. var scene = this.getScene();
  57265. var engine = scene.getEngine();
  57266. if (!this.checkReadyOnEveryCall) {
  57267. if (this._renderId === scene.getRenderId()) {
  57268. if (this._checkCache(scene, mesh, useInstances)) {
  57269. return true;
  57270. }
  57271. }
  57272. }
  57273. // Instances
  57274. var defines = [];
  57275. var attribs = [];
  57276. var fallbacks = new BABYLON.EffectFallbacks();
  57277. if (useInstances) {
  57278. defines.push("#define INSTANCES");
  57279. }
  57280. for (var index = 0; index < this._options.defines.length; index++) {
  57281. defines.push(this._options.defines[index]);
  57282. }
  57283. for (var index = 0; index < this._options.attributes.length; index++) {
  57284. attribs.push(this._options.attributes[index]);
  57285. }
  57286. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57287. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57288. defines.push("#define VERTEXCOLOR");
  57289. }
  57290. // Bones
  57291. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57292. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57293. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57294. if (mesh.numBoneInfluencers > 4) {
  57295. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57296. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57297. }
  57298. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57299. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57300. fallbacks.addCPUSkinningFallback(0, mesh);
  57301. if (this._options.uniforms.indexOf("mBones") === -1) {
  57302. this._options.uniforms.push("mBones");
  57303. }
  57304. }
  57305. else {
  57306. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57307. }
  57308. // Textures
  57309. for (var name in this._textures) {
  57310. if (!this._textures[name].isReady()) {
  57311. return false;
  57312. }
  57313. }
  57314. // Alpha test
  57315. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57316. defines.push("#define ALPHATEST");
  57317. }
  57318. var previousEffect = this._effect;
  57319. var join = defines.join("\n");
  57320. this._effect = engine.createEffect(this._shaderPath, {
  57321. attributes: attribs,
  57322. uniformsNames: this._options.uniforms,
  57323. uniformBuffersNames: this._options.uniformBuffers,
  57324. samplers: this._options.samplers,
  57325. defines: join,
  57326. fallbacks: fallbacks,
  57327. onCompiled: this.onCompiled,
  57328. onError: this.onError
  57329. }, engine);
  57330. if (!this._effect.isReady()) {
  57331. return false;
  57332. }
  57333. if (previousEffect !== this._effect) {
  57334. scene.resetCachedMaterial();
  57335. }
  57336. this._renderId = scene.getRenderId();
  57337. return true;
  57338. };
  57339. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57340. var scene = this.getScene();
  57341. if (!this._effect) {
  57342. return;
  57343. }
  57344. if (this._options.uniforms.indexOf("world") !== -1) {
  57345. this._effect.setMatrix("world", world);
  57346. }
  57347. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57348. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57349. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57350. }
  57351. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57352. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57353. }
  57354. };
  57355. ShaderMaterial.prototype.bind = function (world, mesh) {
  57356. // Std values
  57357. this.bindOnlyWorldMatrix(world);
  57358. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57359. if (this._options.uniforms.indexOf("view") !== -1) {
  57360. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57361. }
  57362. if (this._options.uniforms.indexOf("projection") !== -1) {
  57363. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57364. }
  57365. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57366. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57367. }
  57368. // Bones
  57369. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57370. var name;
  57371. // Texture
  57372. for (name in this._textures) {
  57373. this._effect.setTexture(name, this._textures[name]);
  57374. }
  57375. // Texture arrays
  57376. for (name in this._textureArrays) {
  57377. this._effect.setTextureArray(name, this._textureArrays[name]);
  57378. }
  57379. // Int
  57380. for (name in this._ints) {
  57381. this._effect.setInt(name, this._ints[name]);
  57382. }
  57383. // Float
  57384. for (name in this._floats) {
  57385. this._effect.setFloat(name, this._floats[name]);
  57386. }
  57387. // Floats
  57388. for (name in this._floatsArrays) {
  57389. this._effect.setArray(name, this._floatsArrays[name]);
  57390. }
  57391. // Color3
  57392. for (name in this._colors3) {
  57393. this._effect.setColor3(name, this._colors3[name]);
  57394. }
  57395. for (name in this._colors3Arrays) {
  57396. this._effect.setArray3(name, this._colors3Arrays[name]);
  57397. }
  57398. // Color4
  57399. for (name in this._colors4) {
  57400. var color = this._colors4[name];
  57401. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57402. }
  57403. // Vector2
  57404. for (name in this._vectors2) {
  57405. this._effect.setVector2(name, this._vectors2[name]);
  57406. }
  57407. // Vector3
  57408. for (name in this._vectors3) {
  57409. this._effect.setVector3(name, this._vectors3[name]);
  57410. }
  57411. // Vector4
  57412. for (name in this._vectors4) {
  57413. this._effect.setVector4(name, this._vectors4[name]);
  57414. }
  57415. // Matrix
  57416. for (name in this._matrices) {
  57417. this._effect.setMatrix(name, this._matrices[name]);
  57418. }
  57419. // Matrix 3x3
  57420. for (name in this._matrices3x3) {
  57421. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57422. }
  57423. // Matrix 2x2
  57424. for (name in this._matrices2x2) {
  57425. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57426. }
  57427. // Vector2Array
  57428. for (name in this._vectors2Arrays) {
  57429. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57430. }
  57431. // Vector3Array
  57432. for (name in this._vectors3Arrays) {
  57433. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57434. }
  57435. }
  57436. this._afterBind(mesh);
  57437. };
  57438. ShaderMaterial.prototype.getActiveTextures = function () {
  57439. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57440. for (var name in this._textures) {
  57441. activeTextures.push(this._textures[name]);
  57442. }
  57443. for (var name in this._textureArrays) {
  57444. var array = this._textureArrays[name];
  57445. for (var index = 0; index < array.length; index++) {
  57446. activeTextures.push(array[index]);
  57447. }
  57448. }
  57449. return activeTextures;
  57450. };
  57451. ShaderMaterial.prototype.hasTexture = function (texture) {
  57452. if (_super.prototype.hasTexture.call(this, texture)) {
  57453. return true;
  57454. }
  57455. for (var name in this._textures) {
  57456. if (this._textures[name] === texture) {
  57457. return true;
  57458. }
  57459. }
  57460. for (var name in this._textureArrays) {
  57461. var array = this._textureArrays[name];
  57462. for (var index = 0; index < array.length; index++) {
  57463. if (array[index] === texture) {
  57464. return true;
  57465. }
  57466. }
  57467. }
  57468. return false;
  57469. };
  57470. ShaderMaterial.prototype.clone = function (name) {
  57471. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57472. return newShaderMaterial;
  57473. };
  57474. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57475. if (forceDisposeTextures) {
  57476. var name;
  57477. for (name in this._textures) {
  57478. this._textures[name].dispose();
  57479. }
  57480. for (name in this._textureArrays) {
  57481. var array = this._textureArrays[name];
  57482. for (var index = 0; index < array.length; index++) {
  57483. array[index].dispose();
  57484. }
  57485. }
  57486. }
  57487. this._textures = {};
  57488. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57489. };
  57490. ShaderMaterial.prototype.serialize = function () {
  57491. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57492. serializationObject.customType = "BABYLON.ShaderMaterial";
  57493. serializationObject.options = this._options;
  57494. serializationObject.shaderPath = this._shaderPath;
  57495. var name;
  57496. // Texture
  57497. serializationObject.textures = {};
  57498. for (name in this._textures) {
  57499. serializationObject.textures[name] = this._textures[name].serialize();
  57500. }
  57501. // Texture arrays
  57502. serializationObject.textureArrays = {};
  57503. for (name in this._textureArrays) {
  57504. serializationObject.textureArrays[name] = [];
  57505. var array = this._textureArrays[name];
  57506. for (var index = 0; index < array.length; index++) {
  57507. serializationObject.textureArrays[name].push(array[index].serialize());
  57508. }
  57509. }
  57510. // Float
  57511. serializationObject.floats = {};
  57512. for (name in this._floats) {
  57513. serializationObject.floats[name] = this._floats[name];
  57514. }
  57515. // Float s
  57516. serializationObject.FloatArrays = {};
  57517. for (name in this._floatsArrays) {
  57518. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57519. }
  57520. // Color3
  57521. serializationObject.colors3 = {};
  57522. for (name in this._colors3) {
  57523. serializationObject.colors3[name] = this._colors3[name].asArray();
  57524. }
  57525. // Color3 array
  57526. serializationObject.colors3Arrays = {};
  57527. for (name in this._colors3Arrays) {
  57528. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57529. }
  57530. // Color4
  57531. serializationObject.colors4 = {};
  57532. for (name in this._colors4) {
  57533. serializationObject.colors4[name] = this._colors4[name].asArray();
  57534. }
  57535. // Vector2
  57536. serializationObject.vectors2 = {};
  57537. for (name in this._vectors2) {
  57538. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57539. }
  57540. // Vector3
  57541. serializationObject.vectors3 = {};
  57542. for (name in this._vectors3) {
  57543. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57544. }
  57545. // Vector4
  57546. serializationObject.vectors4 = {};
  57547. for (name in this._vectors4) {
  57548. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57549. }
  57550. // Matrix
  57551. serializationObject.matrices = {};
  57552. for (name in this._matrices) {
  57553. serializationObject.matrices[name] = this._matrices[name].asArray();
  57554. }
  57555. // Matrix 3x3
  57556. serializationObject.matrices3x3 = {};
  57557. for (name in this._matrices3x3) {
  57558. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57559. }
  57560. // Matrix 2x2
  57561. serializationObject.matrices2x2 = {};
  57562. for (name in this._matrices2x2) {
  57563. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57564. }
  57565. // Vector2Array
  57566. serializationObject.vectors2Arrays = {};
  57567. for (name in this._vectors2Arrays) {
  57568. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57569. }
  57570. // Vector3Array
  57571. serializationObject.vectors3Arrays = {};
  57572. for (name in this._vectors3Arrays) {
  57573. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57574. }
  57575. return serializationObject;
  57576. };
  57577. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57578. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57579. var name;
  57580. // Texture
  57581. for (name in source.textures) {
  57582. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57583. }
  57584. // Texture arrays
  57585. for (name in source.textureArrays) {
  57586. var array = source.textureArrays[name];
  57587. var textureArray = new Array();
  57588. for (var index = 0; index < array.length; index++) {
  57589. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57590. }
  57591. material.setTextureArray(name, textureArray);
  57592. }
  57593. // Float
  57594. for (name in source.floats) {
  57595. material.setFloat(name, source.floats[name]);
  57596. }
  57597. // Float s
  57598. for (name in source.floatsArrays) {
  57599. material.setFloats(name, source.floatsArrays[name]);
  57600. }
  57601. // Color3
  57602. for (name in source.colors3) {
  57603. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57604. }
  57605. // Color3 arrays
  57606. for (name in source.colors3Arrays) {
  57607. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57608. if (i % 3 === 0) {
  57609. arr.push([num]);
  57610. }
  57611. else {
  57612. arr[arr.length - 1].push(num);
  57613. }
  57614. return arr;
  57615. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57616. material.setColor3Array(name, colors);
  57617. }
  57618. // Color4
  57619. for (name in source.colors4) {
  57620. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57621. }
  57622. // Vector2
  57623. for (name in source.vectors2) {
  57624. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  57625. }
  57626. // Vector3
  57627. for (name in source.vectors3) {
  57628. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  57629. }
  57630. // Vector4
  57631. for (name in source.vectors4) {
  57632. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  57633. }
  57634. // Matrix
  57635. for (name in source.matrices) {
  57636. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  57637. }
  57638. // Matrix 3x3
  57639. for (name in source.matrices3x3) {
  57640. material.setMatrix3x3(name, source.matrices3x3[name]);
  57641. }
  57642. // Matrix 2x2
  57643. for (name in source.matrices2x2) {
  57644. material.setMatrix2x2(name, source.matrices2x2[name]);
  57645. }
  57646. // Vector2Array
  57647. for (name in source.vectors2Arrays) {
  57648. material.setArray2(name, source.vectors2Arrays[name]);
  57649. }
  57650. // Vector3Array
  57651. for (name in source.vectors3Arrays) {
  57652. material.setArray3(name, source.vectors3Arrays[name]);
  57653. }
  57654. return material;
  57655. };
  57656. return ShaderMaterial;
  57657. }(BABYLON.Material));
  57658. BABYLON.ShaderMaterial = ShaderMaterial;
  57659. })(BABYLON || (BABYLON = {}));
  57660. //# sourceMappingURL=babylon.shaderMaterial.js.map
  57661. var BABYLON;
  57662. (function (BABYLON) {
  57663. var GroundMesh = /** @class */ (function (_super) {
  57664. __extends(GroundMesh, _super);
  57665. function GroundMesh(name, scene) {
  57666. var _this = _super.call(this, name, scene) || this;
  57667. _this.generateOctree = false;
  57668. return _this;
  57669. }
  57670. GroundMesh.prototype.getClassName = function () {
  57671. return "GroundMesh";
  57672. };
  57673. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  57674. get: function () {
  57675. return Math.min(this._subdivisionsX, this._subdivisionsY);
  57676. },
  57677. enumerable: true,
  57678. configurable: true
  57679. });
  57680. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  57681. get: function () {
  57682. return this._subdivisionsX;
  57683. },
  57684. enumerable: true,
  57685. configurable: true
  57686. });
  57687. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  57688. get: function () {
  57689. return this._subdivisionsY;
  57690. },
  57691. enumerable: true,
  57692. configurable: true
  57693. });
  57694. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  57695. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  57696. this._subdivisionsX = chunksCount;
  57697. this._subdivisionsY = chunksCount;
  57698. this.subdivide(chunksCount);
  57699. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  57700. };
  57701. /**
  57702. * Returns a height (y) value in the Worl system :
  57703. * the ground altitude at the coordinates (x, z) expressed in the World system.
  57704. * Returns the ground y position if (x, z) are outside the ground surface.
  57705. */
  57706. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  57707. var world = this.getWorldMatrix();
  57708. var invMat = BABYLON.Tmp.Matrix[5];
  57709. world.invertToRef(invMat);
  57710. var tmpVect = BABYLON.Tmp.Vector3[8];
  57711. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  57712. x = tmpVect.x;
  57713. z = tmpVect.z;
  57714. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57715. return this.position.y;
  57716. }
  57717. if (!this._heightQuads || this._heightQuads.length == 0) {
  57718. this._initHeightQuads();
  57719. this._computeHeightQuads();
  57720. }
  57721. var facet = this._getFacetAt(x, z);
  57722. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  57723. // return y in the World system
  57724. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  57725. return tmpVect.y;
  57726. };
  57727. /**
  57728. * Returns a normalized vector (Vector3) orthogonal to the ground
  57729. * at the ground coordinates (x, z) expressed in the World system.
  57730. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  57731. */
  57732. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  57733. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  57734. this.getNormalAtCoordinatesToRef(x, z, normal);
  57735. return normal;
  57736. };
  57737. /**
  57738. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  57739. * at the ground coordinates (x, z) expressed in the World system.
  57740. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  57741. * Returns the GroundMesh.
  57742. */
  57743. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  57744. var world = this.getWorldMatrix();
  57745. var tmpMat = BABYLON.Tmp.Matrix[5];
  57746. world.invertToRef(tmpMat);
  57747. var tmpVect = BABYLON.Tmp.Vector3[8];
  57748. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  57749. x = tmpVect.x;
  57750. z = tmpVect.z;
  57751. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57752. return this;
  57753. }
  57754. if (!this._heightQuads || this._heightQuads.length == 0) {
  57755. this._initHeightQuads();
  57756. this._computeHeightQuads();
  57757. }
  57758. var facet = this._getFacetAt(x, z);
  57759. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  57760. return this;
  57761. };
  57762. /**
  57763. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  57764. * if the ground has been updated.
  57765. * This can be used in the render loop.
  57766. * Returns the GroundMesh.
  57767. */
  57768. GroundMesh.prototype.updateCoordinateHeights = function () {
  57769. if (!this._heightQuads || this._heightQuads.length == 0) {
  57770. this._initHeightQuads();
  57771. }
  57772. this._computeHeightQuads();
  57773. return this;
  57774. };
  57775. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  57776. GroundMesh.prototype._getFacetAt = function (x, z) {
  57777. // retrieve col and row from x, z coordinates in the ground local system
  57778. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  57779. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  57780. var quad = this._heightQuads[row * this._subdivisionsX + col];
  57781. var facet;
  57782. if (z < quad.slope.x * x + quad.slope.y) {
  57783. facet = quad.facet1;
  57784. }
  57785. else {
  57786. facet = quad.facet2;
  57787. }
  57788. return facet;
  57789. };
  57790. // Creates and populates the heightMap array with "facet" elements :
  57791. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  57792. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57793. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57794. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57795. // Returns the GroundMesh.
  57796. GroundMesh.prototype._initHeightQuads = function () {
  57797. var subdivisionsX = this._subdivisionsX;
  57798. var subdivisionsY = this._subdivisionsY;
  57799. this._heightQuads = new Array();
  57800. for (var row = 0; row < subdivisionsY; row++) {
  57801. for (var col = 0; col < subdivisionsX; col++) {
  57802. 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) };
  57803. this._heightQuads[row * subdivisionsX + col] = quad;
  57804. }
  57805. }
  57806. return this;
  57807. };
  57808. // Compute each quad element values and update the the heightMap array :
  57809. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57810. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57811. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57812. // Returns the GroundMesh.
  57813. GroundMesh.prototype._computeHeightQuads = function () {
  57814. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57815. if (!positions) {
  57816. return this;
  57817. }
  57818. var v1 = BABYLON.Tmp.Vector3[3];
  57819. var v2 = BABYLON.Tmp.Vector3[2];
  57820. var v3 = BABYLON.Tmp.Vector3[1];
  57821. var v4 = BABYLON.Tmp.Vector3[0];
  57822. var v1v2 = BABYLON.Tmp.Vector3[4];
  57823. var v1v3 = BABYLON.Tmp.Vector3[5];
  57824. var v1v4 = BABYLON.Tmp.Vector3[6];
  57825. var norm1 = BABYLON.Tmp.Vector3[7];
  57826. var norm2 = BABYLON.Tmp.Vector3[8];
  57827. var i = 0;
  57828. var j = 0;
  57829. var k = 0;
  57830. var cd = 0; // 2D slope coefficient : z = cd * x + h
  57831. var h = 0;
  57832. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  57833. var d2 = 0;
  57834. var subdivisionsX = this._subdivisionsX;
  57835. var subdivisionsY = this._subdivisionsY;
  57836. for (var row = 0; row < subdivisionsY; row++) {
  57837. for (var col = 0; col < subdivisionsX; col++) {
  57838. i = col * 3;
  57839. j = row * (subdivisionsX + 1) * 3;
  57840. k = (row + 1) * (subdivisionsX + 1) * 3;
  57841. v1.x = positions[j + i];
  57842. v1.y = positions[j + i + 1];
  57843. v1.z = positions[j + i + 2];
  57844. v2.x = positions[j + i + 3];
  57845. v2.y = positions[j + i + 4];
  57846. v2.z = positions[j + i + 5];
  57847. v3.x = positions[k + i];
  57848. v3.y = positions[k + i + 1];
  57849. v3.z = positions[k + i + 2];
  57850. v4.x = positions[k + i + 3];
  57851. v4.y = positions[k + i + 4];
  57852. v4.z = positions[k + i + 5];
  57853. // 2D slope V1V4
  57854. cd = (v4.z - v1.z) / (v4.x - v1.x);
  57855. h = v1.z - cd * v1.x; // v1 belongs to the slope
  57856. // facet equations :
  57857. // we compute each facet normal vector
  57858. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  57859. // we compute the value d by applying the equation to v1 which belongs to the plane
  57860. // then we store the facet equation in a Vector4
  57861. v2.subtractToRef(v1, v1v2);
  57862. v3.subtractToRef(v1, v1v3);
  57863. v4.subtractToRef(v1, v1v4);
  57864. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  57865. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  57866. norm1.normalize();
  57867. norm2.normalize();
  57868. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  57869. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  57870. var quad = this._heightQuads[row * subdivisionsX + col];
  57871. quad.slope.copyFromFloats(cd, h);
  57872. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  57873. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  57874. }
  57875. }
  57876. return this;
  57877. };
  57878. GroundMesh.prototype.serialize = function (serializationObject) {
  57879. _super.prototype.serialize.call(this, serializationObject);
  57880. serializationObject.subdivisionsX = this._subdivisionsX;
  57881. serializationObject.subdivisionsY = this._subdivisionsY;
  57882. serializationObject.minX = this._minX;
  57883. serializationObject.maxX = this._maxX;
  57884. serializationObject.minZ = this._minZ;
  57885. serializationObject.maxZ = this._maxZ;
  57886. serializationObject.width = this._width;
  57887. serializationObject.height = this._height;
  57888. };
  57889. GroundMesh.Parse = function (parsedMesh, scene) {
  57890. var result = new GroundMesh(parsedMesh.name, scene);
  57891. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  57892. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  57893. result._minX = parsedMesh.minX;
  57894. result._maxX = parsedMesh.maxX;
  57895. result._minZ = parsedMesh.minZ;
  57896. result._maxZ = parsedMesh.maxZ;
  57897. result._width = parsedMesh.width;
  57898. result._height = parsedMesh.height;
  57899. return result;
  57900. };
  57901. return GroundMesh;
  57902. }(BABYLON.Mesh));
  57903. BABYLON.GroundMesh = GroundMesh;
  57904. })(BABYLON || (BABYLON = {}));
  57905. //# sourceMappingURL=babylon.groundMesh.js.map
  57906. var BABYLON;
  57907. (function (BABYLON) {
  57908. /**
  57909. * Creates an instance based on a source mesh.
  57910. */
  57911. var InstancedMesh = /** @class */ (function (_super) {
  57912. __extends(InstancedMesh, _super);
  57913. function InstancedMesh(name, source) {
  57914. var _this = _super.call(this, name, source.getScene()) || this;
  57915. source.instances.push(_this);
  57916. _this._sourceMesh = source;
  57917. _this.position.copyFrom(source.position);
  57918. _this.rotation.copyFrom(source.rotation);
  57919. _this.scaling.copyFrom(source.scaling);
  57920. if (source.rotationQuaternion) {
  57921. _this.rotationQuaternion = source.rotationQuaternion.clone();
  57922. }
  57923. _this.infiniteDistance = source.infiniteDistance;
  57924. _this.setPivotMatrix(source.getPivotMatrix());
  57925. _this.refreshBoundingInfo();
  57926. _this._syncSubMeshes();
  57927. return _this;
  57928. }
  57929. /**
  57930. * Returns the string "InstancedMesh".
  57931. */
  57932. InstancedMesh.prototype.getClassName = function () {
  57933. return "InstancedMesh";
  57934. };
  57935. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  57936. // Methods
  57937. get: function () {
  57938. return this._sourceMesh.receiveShadows;
  57939. },
  57940. enumerable: true,
  57941. configurable: true
  57942. });
  57943. Object.defineProperty(InstancedMesh.prototype, "material", {
  57944. get: function () {
  57945. return this._sourceMesh.material;
  57946. },
  57947. enumerable: true,
  57948. configurable: true
  57949. });
  57950. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  57951. get: function () {
  57952. return this._sourceMesh.visibility;
  57953. },
  57954. enumerable: true,
  57955. configurable: true
  57956. });
  57957. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  57958. get: function () {
  57959. return this._sourceMesh.skeleton;
  57960. },
  57961. enumerable: true,
  57962. configurable: true
  57963. });
  57964. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  57965. get: function () {
  57966. return this._sourceMesh.renderingGroupId;
  57967. },
  57968. set: function (value) {
  57969. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  57970. return;
  57971. }
  57972. //no-op with warning
  57973. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  57974. },
  57975. enumerable: true,
  57976. configurable: true
  57977. });
  57978. /**
  57979. * Returns the total number of vertices (integer).
  57980. */
  57981. InstancedMesh.prototype.getTotalVertices = function () {
  57982. return this._sourceMesh.getTotalVertices();
  57983. };
  57984. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  57985. get: function () {
  57986. return this._sourceMesh;
  57987. },
  57988. enumerable: true,
  57989. configurable: true
  57990. });
  57991. /**
  57992. * Is this node ready to be used/rendered
  57993. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  57994. * @return {boolean} is it ready
  57995. */
  57996. InstancedMesh.prototype.isReady = function (completeCheck) {
  57997. if (completeCheck === void 0) { completeCheck = false; }
  57998. return this._sourceMesh.isReady(completeCheck, true);
  57999. };
  58000. /**
  58001. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58002. */
  58003. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58004. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58005. };
  58006. /**
  58007. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58008. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58009. * The `data` are either a numeric array either a Float32Array.
  58010. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58011. * 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).
  58012. * Note that a new underlying VertexBuffer object is created each call.
  58013. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58014. *
  58015. * Possible `kind` values :
  58016. * - BABYLON.VertexBuffer.PositionKind
  58017. * - BABYLON.VertexBuffer.UVKind
  58018. * - BABYLON.VertexBuffer.UV2Kind
  58019. * - BABYLON.VertexBuffer.UV3Kind
  58020. * - BABYLON.VertexBuffer.UV4Kind
  58021. * - BABYLON.VertexBuffer.UV5Kind
  58022. * - BABYLON.VertexBuffer.UV6Kind
  58023. * - BABYLON.VertexBuffer.ColorKind
  58024. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58025. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58026. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58027. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58028. *
  58029. * Returns the Mesh.
  58030. */
  58031. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58032. if (this.sourceMesh) {
  58033. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58034. }
  58035. return this.sourceMesh;
  58036. };
  58037. /**
  58038. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58039. * If the mesh has no geometry, it is simply returned as it is.
  58040. * The `data` are either a numeric array either a Float32Array.
  58041. * No new underlying VertexBuffer object is created.
  58042. * 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.
  58043. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58044. *
  58045. * Possible `kind` values :
  58046. * - BABYLON.VertexBuffer.PositionKind
  58047. * - BABYLON.VertexBuffer.UVKind
  58048. * - BABYLON.VertexBuffer.UV2Kind
  58049. * - BABYLON.VertexBuffer.UV3Kind
  58050. * - BABYLON.VertexBuffer.UV4Kind
  58051. * - BABYLON.VertexBuffer.UV5Kind
  58052. * - BABYLON.VertexBuffer.UV6Kind
  58053. * - BABYLON.VertexBuffer.ColorKind
  58054. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58055. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58056. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58057. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58058. *
  58059. * Returns the Mesh.
  58060. */
  58061. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58062. if (this.sourceMesh) {
  58063. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58064. }
  58065. return this.sourceMesh;
  58066. };
  58067. /**
  58068. * Sets the mesh indices.
  58069. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58070. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58071. * This method creates a new index buffer each call.
  58072. * Returns the Mesh.
  58073. */
  58074. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58075. if (totalVertices === void 0) { totalVertices = null; }
  58076. if (this.sourceMesh) {
  58077. this.sourceMesh.setIndices(indices, totalVertices);
  58078. }
  58079. return this.sourceMesh;
  58080. };
  58081. /**
  58082. * Boolean : True if the mesh owns the requested kind of data.
  58083. */
  58084. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58085. return this._sourceMesh.isVerticesDataPresent(kind);
  58086. };
  58087. /**
  58088. * Returns an array of indices (IndicesArray).
  58089. */
  58090. InstancedMesh.prototype.getIndices = function () {
  58091. return this._sourceMesh.getIndices();
  58092. };
  58093. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58094. get: function () {
  58095. return this._sourceMesh._positions;
  58096. },
  58097. enumerable: true,
  58098. configurable: true
  58099. });
  58100. /**
  58101. * Sets a new updated BoundingInfo to the mesh.
  58102. * Returns the mesh.
  58103. */
  58104. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58105. var meshBB = this._sourceMesh.getBoundingInfo();
  58106. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58107. this._updateBoundingInfo();
  58108. return this;
  58109. };
  58110. InstancedMesh.prototype._preActivate = function () {
  58111. if (this._currentLOD) {
  58112. this._currentLOD._preActivate();
  58113. }
  58114. return this;
  58115. };
  58116. InstancedMesh.prototype._activate = function (renderId) {
  58117. if (this._currentLOD) {
  58118. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58119. }
  58120. return this;
  58121. };
  58122. /**
  58123. * Returns the current associated LOD AbstractMesh.
  58124. */
  58125. InstancedMesh.prototype.getLOD = function (camera) {
  58126. if (!camera) {
  58127. return this;
  58128. }
  58129. var boundingInfo = this.getBoundingInfo();
  58130. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58131. if (this._currentLOD === this.sourceMesh) {
  58132. return this;
  58133. }
  58134. return this._currentLOD;
  58135. };
  58136. InstancedMesh.prototype._syncSubMeshes = function () {
  58137. this.releaseSubMeshes();
  58138. if (this._sourceMesh.subMeshes) {
  58139. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58140. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58141. }
  58142. }
  58143. return this;
  58144. };
  58145. InstancedMesh.prototype._generatePointsArray = function () {
  58146. return this._sourceMesh._generatePointsArray();
  58147. };
  58148. /**
  58149. * Creates a new InstancedMesh from the current mesh.
  58150. * - name (string) : the cloned mesh name
  58151. * - newParent (optional Node) : the optional Node to parent the clone to.
  58152. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58153. *
  58154. * Returns the clone.
  58155. */
  58156. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58157. var result = this._sourceMesh.createInstance(name);
  58158. // Deep copy
  58159. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58160. // Bounding info
  58161. this.refreshBoundingInfo();
  58162. // Parent
  58163. if (newParent) {
  58164. result.parent = newParent;
  58165. }
  58166. if (!doNotCloneChildren) {
  58167. // Children
  58168. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58169. var mesh = this.getScene().meshes[index];
  58170. if (mesh.parent === this) {
  58171. mesh.clone(mesh.name, result);
  58172. }
  58173. }
  58174. }
  58175. result.computeWorldMatrix(true);
  58176. return result;
  58177. };
  58178. /**
  58179. * Disposes the InstancedMesh.
  58180. * Returns nothing.
  58181. */
  58182. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58183. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58184. // Remove from mesh
  58185. var index = this._sourceMesh.instances.indexOf(this);
  58186. this._sourceMesh.instances.splice(index, 1);
  58187. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58188. };
  58189. return InstancedMesh;
  58190. }(BABYLON.AbstractMesh));
  58191. BABYLON.InstancedMesh = InstancedMesh;
  58192. })(BABYLON || (BABYLON = {}));
  58193. //# sourceMappingURL=babylon.instancedMesh.js.map
  58194. var BABYLON;
  58195. (function (BABYLON) {
  58196. var LinesMesh = /** @class */ (function (_super) {
  58197. __extends(LinesMesh, _super);
  58198. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58199. if (scene === void 0) { scene = null; }
  58200. if (parent === void 0) { parent = null; }
  58201. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58202. _this.useVertexColor = useVertexColor;
  58203. _this.useVertexAlpha = useVertexAlpha;
  58204. _this.color = new BABYLON.Color3(1, 1, 1);
  58205. _this.alpha = 1;
  58206. if (source) {
  58207. _this.color = source.color.clone();
  58208. _this.alpha = source.alpha;
  58209. _this.useVertexColor = source.useVertexColor;
  58210. _this.useVertexAlpha = source.useVertexAlpha;
  58211. }
  58212. _this._intersectionThreshold = 0.1;
  58213. var defines = [];
  58214. var options = {
  58215. attributes: [BABYLON.VertexBuffer.PositionKind],
  58216. uniforms: ["world", "viewProjection"],
  58217. needAlphaBlending: true,
  58218. defines: defines
  58219. };
  58220. if (useVertexAlpha === false) {
  58221. options.needAlphaBlending = false;
  58222. }
  58223. if (!useVertexColor) {
  58224. options.uniforms.push("color");
  58225. }
  58226. else {
  58227. options.defines.push("#define VERTEXCOLOR");
  58228. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58229. }
  58230. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58231. return _this;
  58232. }
  58233. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58234. /**
  58235. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58236. * This margin is expressed in world space coordinates, so its value may vary.
  58237. * Default value is 0.1
  58238. * @returns the intersection Threshold value.
  58239. */
  58240. get: function () {
  58241. return this._intersectionThreshold;
  58242. },
  58243. /**
  58244. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58245. * This margin is expressed in world space coordinates, so its value may vary.
  58246. * @param value the new threshold to apply
  58247. */
  58248. set: function (value) {
  58249. if (this._intersectionThreshold === value) {
  58250. return;
  58251. }
  58252. this._intersectionThreshold = value;
  58253. if (this.geometry) {
  58254. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58255. }
  58256. },
  58257. enumerable: true,
  58258. configurable: true
  58259. });
  58260. /**
  58261. * Returns the string "LineMesh"
  58262. */
  58263. LinesMesh.prototype.getClassName = function () {
  58264. return "LinesMesh";
  58265. };
  58266. Object.defineProperty(LinesMesh.prototype, "material", {
  58267. /**
  58268. * @hidden
  58269. */
  58270. get: function () {
  58271. return this._colorShader;
  58272. },
  58273. /**
  58274. * @hidden
  58275. */
  58276. set: function (value) {
  58277. // Do nothing
  58278. },
  58279. enumerable: true,
  58280. configurable: true
  58281. });
  58282. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58283. /**
  58284. * @hidden
  58285. */
  58286. get: function () {
  58287. return false;
  58288. },
  58289. enumerable: true,
  58290. configurable: true
  58291. });
  58292. LinesMesh.prototype.createInstance = function (name) {
  58293. throw new Error("LinesMeshes do not support createInstance.");
  58294. };
  58295. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58296. if (!this._geometry) {
  58297. return this;
  58298. }
  58299. // VBOs
  58300. this._geometry._bind(this._colorShader.getEffect());
  58301. // Color
  58302. if (!this.useVertexColor) {
  58303. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58304. }
  58305. return this;
  58306. };
  58307. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58308. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58309. return this;
  58310. }
  58311. var engine = this.getScene().getEngine();
  58312. // Draw order
  58313. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58314. return this;
  58315. };
  58316. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58317. this._colorShader.dispose();
  58318. _super.prototype.dispose.call(this, doNotRecurse);
  58319. };
  58320. /**
  58321. * Returns a new LineMesh object cloned from the current one.
  58322. */
  58323. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58324. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58325. };
  58326. return LinesMesh;
  58327. }(BABYLON.Mesh));
  58328. BABYLON.LinesMesh = LinesMesh;
  58329. })(BABYLON || (BABYLON = {}));
  58330. //# sourceMappingURL=babylon.linesMesh.js.map
  58331. var BABYLON;
  58332. (function (BABYLON) {
  58333. /**
  58334. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58335. * The underlying implementation relies on an associative array to ensure the best performances.
  58336. * The value can be anything including 'null' but except 'undefined'
  58337. */
  58338. var StringDictionary = /** @class */ (function () {
  58339. function StringDictionary() {
  58340. this._count = 0;
  58341. this._data = {};
  58342. }
  58343. /**
  58344. * This will clear this dictionary and copy the content from the 'source' one.
  58345. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58346. * @param source the dictionary to take the content from and copy to this dictionary
  58347. */
  58348. StringDictionary.prototype.copyFrom = function (source) {
  58349. var _this = this;
  58350. this.clear();
  58351. source.forEach(function (t, v) { return _this.add(t, v); });
  58352. };
  58353. /**
  58354. * Get a value based from its key
  58355. * @param key the given key to get the matching value from
  58356. * @return the value if found, otherwise undefined is returned
  58357. */
  58358. StringDictionary.prototype.get = function (key) {
  58359. var val = this._data[key];
  58360. if (val !== undefined) {
  58361. return val;
  58362. }
  58363. return undefined;
  58364. };
  58365. /**
  58366. * Get a value from its key or add it if it doesn't exist.
  58367. * This method will ensure you that a given key/data will be present in the dictionary.
  58368. * @param key the given key to get the matching value from
  58369. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58370. * The factory will only be invoked if there's no data for the given key.
  58371. * @return the value corresponding to the key.
  58372. */
  58373. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58374. var val = this.get(key);
  58375. if (val !== undefined) {
  58376. return val;
  58377. }
  58378. val = factory(key);
  58379. if (val) {
  58380. this.add(key, val);
  58381. }
  58382. return val;
  58383. };
  58384. /**
  58385. * Get a value from its key if present in the dictionary otherwise add it
  58386. * @param key the key to get the value from
  58387. * @param val if there's no such key/value pair in the dictionary add it with this value
  58388. * @return the value corresponding to the key
  58389. */
  58390. StringDictionary.prototype.getOrAdd = function (key, val) {
  58391. var curVal = this.get(key);
  58392. if (curVal !== undefined) {
  58393. return curVal;
  58394. }
  58395. this.add(key, val);
  58396. return val;
  58397. };
  58398. /**
  58399. * Check if there's a given key in the dictionary
  58400. * @param key the key to check for
  58401. * @return true if the key is present, false otherwise
  58402. */
  58403. StringDictionary.prototype.contains = function (key) {
  58404. return this._data[key] !== undefined;
  58405. };
  58406. /**
  58407. * Add a new key and its corresponding value
  58408. * @param key the key to add
  58409. * @param value the value corresponding to the key
  58410. * @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
  58411. */
  58412. StringDictionary.prototype.add = function (key, value) {
  58413. if (this._data[key] !== undefined) {
  58414. return false;
  58415. }
  58416. this._data[key] = value;
  58417. ++this._count;
  58418. return true;
  58419. };
  58420. StringDictionary.prototype.set = function (key, value) {
  58421. if (this._data[key] === undefined) {
  58422. return false;
  58423. }
  58424. this._data[key] = value;
  58425. return true;
  58426. };
  58427. /**
  58428. * Get the element of the given key and remove it from the dictionary
  58429. * @param key
  58430. */
  58431. StringDictionary.prototype.getAndRemove = function (key) {
  58432. var val = this.get(key);
  58433. if (val !== undefined) {
  58434. delete this._data[key];
  58435. --this._count;
  58436. return val;
  58437. }
  58438. return null;
  58439. };
  58440. /**
  58441. * Remove a key/value from the dictionary.
  58442. * @param key the key to remove
  58443. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58444. */
  58445. StringDictionary.prototype.remove = function (key) {
  58446. if (this.contains(key)) {
  58447. delete this._data[key];
  58448. --this._count;
  58449. return true;
  58450. }
  58451. return false;
  58452. };
  58453. /**
  58454. * Clear the whole content of the dictionary
  58455. */
  58456. StringDictionary.prototype.clear = function () {
  58457. this._data = {};
  58458. this._count = 0;
  58459. };
  58460. Object.defineProperty(StringDictionary.prototype, "count", {
  58461. get: function () {
  58462. return this._count;
  58463. },
  58464. enumerable: true,
  58465. configurable: true
  58466. });
  58467. /**
  58468. * Execute a callback on each key/val of the dictionary.
  58469. * Note that you can remove any element in this dictionary in the callback implementation
  58470. * @param callback the callback to execute on a given key/value pair
  58471. */
  58472. StringDictionary.prototype.forEach = function (callback) {
  58473. for (var cur in this._data) {
  58474. var val = this._data[cur];
  58475. callback(cur, val);
  58476. }
  58477. };
  58478. /**
  58479. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58480. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58481. * Note that you can remove any element in this dictionary in the callback implementation
  58482. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58483. */
  58484. StringDictionary.prototype.first = function (callback) {
  58485. for (var cur in this._data) {
  58486. var val = this._data[cur];
  58487. var res = callback(cur, val);
  58488. if (res) {
  58489. return res;
  58490. }
  58491. }
  58492. return null;
  58493. };
  58494. return StringDictionary;
  58495. }());
  58496. BABYLON.StringDictionary = StringDictionary;
  58497. })(BABYLON || (BABYLON = {}));
  58498. //# sourceMappingURL=babylon.stringDictionary.js.map
  58499. var BABYLON;
  58500. (function (BABYLON) {
  58501. var Debug;
  58502. (function (Debug) {
  58503. /**
  58504. * Class used to render a debug view of a given skeleton
  58505. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  58506. */
  58507. var SkeletonViewer = /** @class */ (function () {
  58508. /**
  58509. * Creates a new SkeletonViewer
  58510. * @param skeleton defines the skeleton to render
  58511. * @param mesh defines the mesh attached to the skeleton
  58512. * @param scene defines the hosting scene
  58513. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  58514. * @param renderingGroupId defines the rendering group id to use with the viewer
  58515. */
  58516. function SkeletonViewer(
  58517. /** defines the skeleton to render */
  58518. skeleton,
  58519. /** defines the mesh attached to the skeleton */
  58520. mesh, scene,
  58521. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  58522. autoUpdateBonesMatrices,
  58523. /** defines the rendering group id to use with the viewer */
  58524. renderingGroupId) {
  58525. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58526. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58527. this.skeleton = skeleton;
  58528. this.mesh = mesh;
  58529. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58530. this.renderingGroupId = renderingGroupId;
  58531. /** Gets or sets the color used to render the skeleton */
  58532. this.color = BABYLON.Color3.White();
  58533. this._debugLines = new Array();
  58534. this._isEnabled = false;
  58535. this._scene = scene;
  58536. this.update();
  58537. this._renderFunction = this.update.bind(this);
  58538. }
  58539. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58540. get: function () {
  58541. return this._isEnabled;
  58542. },
  58543. /** Gets or sets a boolean indicating if the viewer is enabled */
  58544. set: function (value) {
  58545. if (this._isEnabled === value) {
  58546. return;
  58547. }
  58548. this._isEnabled = value;
  58549. if (value) {
  58550. this._scene.registerBeforeRender(this._renderFunction);
  58551. }
  58552. else {
  58553. this._scene.unregisterBeforeRender(this._renderFunction);
  58554. }
  58555. },
  58556. enumerable: true,
  58557. configurable: true
  58558. });
  58559. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58560. if (x === void 0) { x = 0; }
  58561. if (y === void 0) { y = 0; }
  58562. if (z === void 0) { z = 0; }
  58563. var tmat = BABYLON.Tmp.Matrix[0];
  58564. var parentBone = bone.getParent();
  58565. tmat.copyFrom(bone.getLocalMatrix());
  58566. if (x !== 0 || y !== 0 || z !== 0) {
  58567. var tmat2 = BABYLON.Tmp.Matrix[1];
  58568. BABYLON.Matrix.IdentityToRef(tmat2);
  58569. tmat2.m[12] = x;
  58570. tmat2.m[13] = y;
  58571. tmat2.m[14] = z;
  58572. tmat2.multiplyToRef(tmat, tmat);
  58573. }
  58574. if (parentBone) {
  58575. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58576. }
  58577. tmat.multiplyToRef(meshMat, tmat);
  58578. position.x = tmat.m[12];
  58579. position.y = tmat.m[13];
  58580. position.z = tmat.m[14];
  58581. };
  58582. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58583. var len = bones.length;
  58584. var meshPos = this.mesh.position;
  58585. for (var i = 0; i < len; i++) {
  58586. var bone = bones[i];
  58587. var points = this._debugLines[i];
  58588. if (!points) {
  58589. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58590. this._debugLines[i] = points;
  58591. }
  58592. this._getBonePosition(points[0], bone, meshMat);
  58593. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58594. points[0].subtractInPlace(meshPos);
  58595. points[1].subtractInPlace(meshPos);
  58596. }
  58597. };
  58598. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58599. var len = bones.length;
  58600. var boneNum = 0;
  58601. var meshPos = this.mesh.position;
  58602. for (var i = len - 1; i >= 0; i--) {
  58603. var childBone = bones[i];
  58604. var parentBone = childBone.getParent();
  58605. if (!parentBone) {
  58606. continue;
  58607. }
  58608. var points = this._debugLines[boneNum];
  58609. if (!points) {
  58610. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58611. this._debugLines[boneNum] = points;
  58612. }
  58613. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58614. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58615. points[0].subtractInPlace(meshPos);
  58616. points[1].subtractInPlace(meshPos);
  58617. boneNum++;
  58618. }
  58619. };
  58620. /** Update the viewer to sync with current skeleton state */
  58621. SkeletonViewer.prototype.update = function () {
  58622. if (this.autoUpdateBonesMatrices) {
  58623. this.skeleton.computeAbsoluteTransforms();
  58624. }
  58625. if (this.skeleton.bones[0].length === undefined) {
  58626. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58627. }
  58628. else {
  58629. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58630. }
  58631. if (!this._debugMesh) {
  58632. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  58633. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58634. }
  58635. else {
  58636. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58637. }
  58638. this._debugMesh.position.copyFrom(this.mesh.position);
  58639. this._debugMesh.color = this.color;
  58640. };
  58641. /** Release associated resources */
  58642. SkeletonViewer.prototype.dispose = function () {
  58643. if (this._debugMesh) {
  58644. this.isEnabled = false;
  58645. this._debugMesh.dispose();
  58646. this._debugMesh = null;
  58647. }
  58648. };
  58649. return SkeletonViewer;
  58650. }());
  58651. Debug.SkeletonViewer = SkeletonViewer;
  58652. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58653. })(BABYLON || (BABYLON = {}));
  58654. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58655. /**
  58656. * Module Debug contains the (visual) components to debug a scene correctly
  58657. */
  58658. var BABYLON;
  58659. (function (BABYLON) {
  58660. var Debug;
  58661. (function (Debug) {
  58662. /**
  58663. * The Axes viewer will show 3 axes in a specific point in space
  58664. */
  58665. var AxesViewer = /** @class */ (function () {
  58666. /**
  58667. * Creates a new AxesViewer
  58668. * @param scene defines the hosting scene
  58669. * @param scaleLines defines a number used to scale line length (1 by default)
  58670. */
  58671. function AxesViewer(scene, scaleLines) {
  58672. if (scaleLines === void 0) { scaleLines = 1; }
  58673. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58674. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58675. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58676. /**
  58677. * Gets or sets a number used to scale line length
  58678. */
  58679. this.scaleLines = 1;
  58680. this.scaleLines = scaleLines;
  58681. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58682. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58683. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58684. this._xmesh.renderingGroupId = 2;
  58685. this._ymesh.renderingGroupId = 2;
  58686. this._zmesh.renderingGroupId = 2;
  58687. this._xmesh.material.checkReadyOnlyOnce = true;
  58688. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58689. this._ymesh.material.checkReadyOnlyOnce = true;
  58690. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58691. this._zmesh.material.checkReadyOnlyOnce = true;
  58692. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58693. this.scene = scene;
  58694. }
  58695. /**
  58696. * Force the viewer to update
  58697. * @param position defines the position of the viewer
  58698. * @param xaxis defines the x axis of the viewer
  58699. * @param yaxis defines the y axis of the viewer
  58700. * @param zaxis defines the z axis of the viewer
  58701. */
  58702. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58703. var scaleLines = this.scaleLines;
  58704. if (this._xmesh) {
  58705. this._xmesh.position.copyFrom(position);
  58706. }
  58707. if (this._ymesh) {
  58708. this._ymesh.position.copyFrom(position);
  58709. }
  58710. if (this._zmesh) {
  58711. this._zmesh.position.copyFrom(position);
  58712. }
  58713. var point2 = this._xline[1];
  58714. point2.x = xaxis.x * scaleLines;
  58715. point2.y = xaxis.y * scaleLines;
  58716. point2.z = xaxis.z * scaleLines;
  58717. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  58718. point2 = this._yline[1];
  58719. point2.x = yaxis.x * scaleLines;
  58720. point2.y = yaxis.y * scaleLines;
  58721. point2.z = yaxis.z * scaleLines;
  58722. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  58723. point2 = this._zline[1];
  58724. point2.x = zaxis.x * scaleLines;
  58725. point2.y = zaxis.y * scaleLines;
  58726. point2.z = zaxis.z * scaleLines;
  58727. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  58728. };
  58729. /** Releases resources */
  58730. AxesViewer.prototype.dispose = function () {
  58731. if (this._xmesh) {
  58732. this._xmesh.dispose();
  58733. }
  58734. if (this._ymesh) {
  58735. this._ymesh.dispose();
  58736. }
  58737. if (this._zmesh) {
  58738. this._zmesh.dispose();
  58739. }
  58740. this._xmesh = null;
  58741. this._ymesh = null;
  58742. this._zmesh = null;
  58743. this.scene = null;
  58744. };
  58745. return AxesViewer;
  58746. }());
  58747. Debug.AxesViewer = AxesViewer;
  58748. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58749. })(BABYLON || (BABYLON = {}));
  58750. //# sourceMappingURL=babylon.axesViewer.js.map
  58751. var BABYLON;
  58752. (function (BABYLON) {
  58753. var Debug;
  58754. (function (Debug) {
  58755. /**
  58756. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  58757. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  58758. */
  58759. var BoneAxesViewer = /** @class */ (function (_super) {
  58760. __extends(BoneAxesViewer, _super);
  58761. /**
  58762. * Creates a new BoneAxesViewer
  58763. * @param scene defines the hosting scene
  58764. * @param bone defines the target bone
  58765. * @param mesh defines the target mesh
  58766. * @param scaleLines defines a scaling factor for line length (1 by default)
  58767. */
  58768. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58769. if (scaleLines === void 0) { scaleLines = 1; }
  58770. var _this = _super.call(this, scene, scaleLines) || this;
  58771. /** Gets current position */
  58772. _this.pos = BABYLON.Vector3.Zero();
  58773. /** Gets direction of X axis */
  58774. _this.xaxis = BABYLON.Vector3.Zero();
  58775. /** Gets direction of Y axis */
  58776. _this.yaxis = BABYLON.Vector3.Zero();
  58777. /** Gets direction of Z axis */
  58778. _this.zaxis = BABYLON.Vector3.Zero();
  58779. _this.mesh = mesh;
  58780. _this.bone = bone;
  58781. return _this;
  58782. }
  58783. /**
  58784. * Force the viewer to update
  58785. */
  58786. BoneAxesViewer.prototype.update = function () {
  58787. if (!this.mesh || !this.bone) {
  58788. return;
  58789. }
  58790. var bone = this.bone;
  58791. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58792. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58793. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58794. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58795. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58796. };
  58797. /** Releases resources */
  58798. BoneAxesViewer.prototype.dispose = function () {
  58799. if (this.mesh) {
  58800. this.mesh = null;
  58801. this.bone = null;
  58802. _super.prototype.dispose.call(this);
  58803. }
  58804. };
  58805. return BoneAxesViewer;
  58806. }(Debug.AxesViewer));
  58807. Debug.BoneAxesViewer = BoneAxesViewer;
  58808. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58809. })(BABYLON || (BABYLON = {}));
  58810. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58811. var BABYLON;
  58812. (function (BABYLON) {
  58813. var RayHelper = /** @class */ (function () {
  58814. function RayHelper(ray) {
  58815. this.ray = ray;
  58816. }
  58817. RayHelper.CreateAndShow = function (ray, scene, color) {
  58818. var helper = new RayHelper(ray);
  58819. helper.show(scene, color);
  58820. return helper;
  58821. };
  58822. RayHelper.prototype.show = function (scene, color) {
  58823. if (!this._renderFunction && this.ray) {
  58824. var ray = this.ray;
  58825. this._renderFunction = this._render.bind(this);
  58826. this._scene = scene;
  58827. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  58828. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  58829. if (this._renderFunction) {
  58830. this._scene.registerBeforeRender(this._renderFunction);
  58831. }
  58832. }
  58833. if (color && this._renderLine) {
  58834. this._renderLine.color.copyFrom(color);
  58835. }
  58836. };
  58837. RayHelper.prototype.hide = function () {
  58838. if (this._renderFunction && this._scene) {
  58839. this._scene.unregisterBeforeRender(this._renderFunction);
  58840. this._scene = null;
  58841. this._renderFunction = null;
  58842. if (this._renderLine) {
  58843. this._renderLine.dispose();
  58844. this._renderLine = null;
  58845. }
  58846. this._renderPoints = [];
  58847. }
  58848. };
  58849. RayHelper.prototype._render = function () {
  58850. var ray = this.ray;
  58851. if (!ray) {
  58852. return;
  58853. }
  58854. var point = this._renderPoints[1];
  58855. var len = Math.min(ray.length, 1000000);
  58856. point.copyFrom(ray.direction);
  58857. point.scaleInPlace(len);
  58858. point.addInPlace(ray.origin);
  58859. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  58860. };
  58861. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  58862. this._attachedToMesh = mesh;
  58863. var ray = this.ray;
  58864. if (!ray) {
  58865. return;
  58866. }
  58867. if (!ray.direction) {
  58868. ray.direction = BABYLON.Vector3.Zero();
  58869. }
  58870. if (!ray.origin) {
  58871. ray.origin = BABYLON.Vector3.Zero();
  58872. }
  58873. if (length) {
  58874. ray.length = length;
  58875. }
  58876. if (!meshSpaceOrigin) {
  58877. meshSpaceOrigin = BABYLON.Vector3.Zero();
  58878. }
  58879. if (!meshSpaceDirection) {
  58880. // -1 so that this will work with Mesh.lookAt
  58881. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  58882. }
  58883. if (!this._meshSpaceDirection) {
  58884. this._meshSpaceDirection = meshSpaceDirection.clone();
  58885. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  58886. }
  58887. else {
  58888. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  58889. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  58890. }
  58891. if (!this._updateToMeshFunction) {
  58892. this._updateToMeshFunction = this._updateToMesh.bind(this);
  58893. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  58894. }
  58895. this._updateToMesh();
  58896. };
  58897. RayHelper.prototype.detachFromMesh = function () {
  58898. if (this._attachedToMesh) {
  58899. if (this._updateToMeshFunction) {
  58900. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  58901. }
  58902. this._attachedToMesh = null;
  58903. this._updateToMeshFunction = null;
  58904. }
  58905. };
  58906. RayHelper.prototype._updateToMesh = function () {
  58907. var ray = this.ray;
  58908. if (!this._attachedToMesh || !ray) {
  58909. return;
  58910. }
  58911. if (this._attachedToMesh._isDisposed) {
  58912. this.detachFromMesh();
  58913. return;
  58914. }
  58915. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  58916. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  58917. };
  58918. RayHelper.prototype.dispose = function () {
  58919. this.hide();
  58920. this.detachFromMesh();
  58921. this.ray = null;
  58922. };
  58923. return RayHelper;
  58924. }());
  58925. BABYLON.RayHelper = RayHelper;
  58926. })(BABYLON || (BABYLON = {}));
  58927. //# sourceMappingURL=babylon.rayHelper.js.map
  58928. var BABYLON;
  58929. (function (BABYLON) {
  58930. // load the inspector using require, if not present in the global namespace.
  58931. var DebugLayer = /** @class */ (function () {
  58932. function DebugLayer(scene) {
  58933. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58934. this.onPropertyChangedObservable = new BABYLON.Observable();
  58935. this._scene = scene;
  58936. }
  58937. /** Creates the inspector window. */
  58938. DebugLayer.prototype._createInspector = function (config) {
  58939. if (config === void 0) { config = {}; }
  58940. var popup = config.popup || false;
  58941. var initialTab = config.initialTab || 0;
  58942. var parentElement = config.parentElement || null;
  58943. if (!this._inspector) {
  58944. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58945. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  58946. } // else nothing to do as instance is already created
  58947. };
  58948. DebugLayer.prototype.isVisible = function () {
  58949. if (!this._inspector) {
  58950. return false;
  58951. }
  58952. return true;
  58953. };
  58954. DebugLayer.prototype.hide = function () {
  58955. if (this._inspector) {
  58956. try {
  58957. this._inspector.dispose();
  58958. }
  58959. catch (e) {
  58960. // If the inspector has been removed directly from the inspector tool
  58961. }
  58962. this.onPropertyChangedObservable.clear();
  58963. this._inspector = null;
  58964. }
  58965. };
  58966. /**
  58967. *
  58968. * Launch the debugLayer.
  58969. *
  58970. * initialTab:
  58971. * | Value | Tab Name |
  58972. * | --- | --- |
  58973. * | 0 | Scene |
  58974. * | 1 | Console |
  58975. * | 2 | Stats |
  58976. * | 3 | Textures |
  58977. * | 4 | Mesh |
  58978. * | 5 | Light |
  58979. * | 6 | Material |
  58980. * | 7 | GLTF |
  58981. * | 8 | GUI |
  58982. * | 9 | Physics |
  58983. * | 10 | Camera |
  58984. * | 11 | Audio |
  58985. *
  58986. */
  58987. DebugLayer.prototype.show = function (config) {
  58988. if (config === void 0) { config = {}; }
  58989. if (typeof this.BJSINSPECTOR == 'undefined') {
  58990. // Load inspector and add it to the DOM
  58991. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  58992. }
  58993. else {
  58994. // Otherwise creates the inspector
  58995. this._createInspector(config);
  58996. }
  58997. };
  58998. /**
  58999. * Gets the active tab
  59000. * @return the index of the active tab or -1 if the inspector is hidden
  59001. */
  59002. DebugLayer.prototype.getActiveTab = function () {
  59003. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  59004. };
  59005. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  59006. return DebugLayer;
  59007. }());
  59008. BABYLON.DebugLayer = DebugLayer;
  59009. })(BABYLON || (BABYLON = {}));
  59010. //# sourceMappingURL=babylon.debugLayer.js.map
  59011. var BABYLON;
  59012. (function (BABYLON) {
  59013. var Debug;
  59014. (function (Debug) {
  59015. /**
  59016. * Used to show the physics impostor around the specific mesh
  59017. */
  59018. var PhysicsViewer = /** @class */ (function () {
  59019. /**
  59020. * Creates a new PhysicsViewer
  59021. * @param scene defines the hosting scene
  59022. */
  59023. function PhysicsViewer(scene) {
  59024. /** @hidden */
  59025. this._impostors = [];
  59026. /** @hidden */
  59027. this._meshes = [];
  59028. /** @hidden */
  59029. this._numMeshes = 0;
  59030. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59031. var physicEngine = this._scene.getPhysicsEngine();
  59032. if (physicEngine) {
  59033. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  59034. }
  59035. }
  59036. /** @hidden */
  59037. PhysicsViewer.prototype._updateDebugMeshes = function () {
  59038. var plugin = this._physicsEnginePlugin;
  59039. for (var i = 0; i < this._numMeshes; i++) {
  59040. var impostor = this._impostors[i];
  59041. if (!impostor) {
  59042. continue;
  59043. }
  59044. if (impostor.isDisposed) {
  59045. this.hideImpostor(this._impostors[i--]);
  59046. }
  59047. else {
  59048. var mesh = this._meshes[i];
  59049. if (mesh && plugin) {
  59050. plugin.syncMeshWithImpostor(mesh, impostor);
  59051. }
  59052. }
  59053. }
  59054. };
  59055. /**
  59056. * Renders a specified physic impostor
  59057. * @param impostor defines the impostor to render
  59058. */
  59059. PhysicsViewer.prototype.showImpostor = function (impostor) {
  59060. if (!this._scene) {
  59061. return;
  59062. }
  59063. for (var i = 0; i < this._numMeshes; i++) {
  59064. if (this._impostors[i] == impostor) {
  59065. return;
  59066. }
  59067. }
  59068. var debugMesh = this._getDebugMesh(impostor, this._scene);
  59069. if (debugMesh) {
  59070. this._impostors[this._numMeshes] = impostor;
  59071. this._meshes[this._numMeshes] = debugMesh;
  59072. if (this._numMeshes === 0) {
  59073. this._renderFunction = this._updateDebugMeshes.bind(this);
  59074. this._scene.registerBeforeRender(this._renderFunction);
  59075. }
  59076. this._numMeshes++;
  59077. }
  59078. };
  59079. /**
  59080. * Hides a specified physic impostor
  59081. * @param impostor defines the impostor to hide
  59082. */
  59083. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  59084. if (!impostor || !this._scene) {
  59085. return;
  59086. }
  59087. var removed = false;
  59088. for (var i = 0; i < this._numMeshes; i++) {
  59089. if (this._impostors[i] == impostor) {
  59090. var mesh = this._meshes[i];
  59091. if (!mesh) {
  59092. continue;
  59093. }
  59094. this._scene.removeMesh(mesh);
  59095. mesh.dispose();
  59096. this._numMeshes--;
  59097. if (this._numMeshes > 0) {
  59098. this._meshes[i] = this._meshes[this._numMeshes];
  59099. this._impostors[i] = this._impostors[this._numMeshes];
  59100. this._meshes[this._numMeshes] = null;
  59101. this._impostors[this._numMeshes] = null;
  59102. }
  59103. else {
  59104. this._meshes[0] = null;
  59105. this._impostors[0] = null;
  59106. }
  59107. removed = true;
  59108. break;
  59109. }
  59110. }
  59111. if (removed && this._numMeshes === 0) {
  59112. this._scene.unregisterBeforeRender(this._renderFunction);
  59113. }
  59114. };
  59115. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  59116. if (!this._debugMaterial) {
  59117. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59118. this._debugMaterial.wireframe = true;
  59119. }
  59120. return this._debugMaterial;
  59121. };
  59122. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  59123. if (!this._debugBoxMesh) {
  59124. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59125. this._debugBoxMesh.renderingGroupId = 1;
  59126. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59127. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59128. scene.removeMesh(this._debugBoxMesh);
  59129. }
  59130. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59131. };
  59132. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  59133. if (!this._debugSphereMesh) {
  59134. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59135. this._debugSphereMesh.renderingGroupId = 1;
  59136. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59137. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59138. scene.removeMesh(this._debugSphereMesh);
  59139. }
  59140. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59141. };
  59142. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  59143. var mesh = null;
  59144. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  59145. mesh = this._getDebugBoxMesh(scene);
  59146. impostor.getBoxSizeToRef(mesh.scaling);
  59147. }
  59148. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  59149. mesh = this._getDebugSphereMesh(scene);
  59150. var radius = impostor.getRadius();
  59151. mesh.scaling.x = radius * 2;
  59152. mesh.scaling.y = radius * 2;
  59153. mesh.scaling.z = radius * 2;
  59154. }
  59155. return mesh;
  59156. };
  59157. /** Releases all resources */
  59158. PhysicsViewer.prototype.dispose = function () {
  59159. for (var i = 0; i < this._numMeshes; i++) {
  59160. this.hideImpostor(this._impostors[i]);
  59161. }
  59162. if (this._debugBoxMesh) {
  59163. this._debugBoxMesh.dispose();
  59164. }
  59165. if (this._debugSphereMesh) {
  59166. this._debugSphereMesh.dispose();
  59167. }
  59168. if (this._debugMaterial) {
  59169. this._debugMaterial.dispose();
  59170. }
  59171. this._impostors.length = 0;
  59172. this._scene = null;
  59173. this._physicsEnginePlugin = null;
  59174. };
  59175. return PhysicsViewer;
  59176. }());
  59177. Debug.PhysicsViewer = PhysicsViewer;
  59178. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59179. })(BABYLON || (BABYLON = {}));
  59180. //# sourceMappingURL=babylon.physicsViewer.js.map
  59181. var BABYLON;
  59182. (function (BABYLON) {
  59183. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  59184. get: function () {
  59185. return this._forceShowBoundingBoxes || false;
  59186. },
  59187. set: function (value) {
  59188. this._forceShowBoundingBoxes = value;
  59189. // Lazyly creates a BB renderer if needed.
  59190. if (value) {
  59191. this.getBoundingBoxRenderer();
  59192. }
  59193. },
  59194. enumerable: true,
  59195. configurable: true
  59196. });
  59197. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  59198. if (!this._boundingBoxRenderer) {
  59199. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  59200. }
  59201. return this._boundingBoxRenderer;
  59202. };
  59203. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  59204. get: function () {
  59205. return this._showBoundingBox || false;
  59206. },
  59207. set: function (value) {
  59208. this._showBoundingBox = value;
  59209. // Lazyly creates a BB renderer if needed.
  59210. if (value) {
  59211. this.getScene().getBoundingBoxRenderer();
  59212. }
  59213. },
  59214. enumerable: true,
  59215. configurable: true
  59216. });
  59217. var BoundingBoxRenderer = /** @class */ (function () {
  59218. function BoundingBoxRenderer(scene) {
  59219. /**
  59220. * The component name helpfull to identify the component in the list of scene components.
  59221. */
  59222. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  59223. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59224. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59225. this.showBackLines = true;
  59226. this.renderList = new BABYLON.SmartArray(32);
  59227. this._vertexBuffers = {};
  59228. this.scene = scene;
  59229. scene._addComponent(this);
  59230. }
  59231. /**
  59232. * Registers the component in a given scene
  59233. */
  59234. BoundingBoxRenderer.prototype.register = function () {
  59235. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  59236. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  59237. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  59238. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  59239. };
  59240. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  59241. if (mesh.showSubMeshesBoundingBox) {
  59242. var boundingInfo = subMesh.getBoundingInfo();
  59243. if (boundingInfo !== null && boundingInfo !== undefined) {
  59244. this.renderList.push(boundingInfo.boundingBox);
  59245. }
  59246. }
  59247. };
  59248. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  59249. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  59250. var boundingInfo = sourceMesh.getBoundingInfo();
  59251. this.renderList.push(boundingInfo.boundingBox);
  59252. }
  59253. };
  59254. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59255. if (this._colorShader) {
  59256. return;
  59257. }
  59258. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  59259. attributes: [BABYLON.VertexBuffer.PositionKind],
  59260. uniforms: ["world", "viewProjection", "color"]
  59261. });
  59262. var engine = this.scene.getEngine();
  59263. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  59264. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59265. this._createIndexBuffer();
  59266. };
  59267. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  59268. var engine = this.scene.getEngine();
  59269. 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]);
  59270. };
  59271. /**
  59272. * Rebuilds the elements related to this component in case of
  59273. * context lost for instance.
  59274. */
  59275. BoundingBoxRenderer.prototype.rebuild = function () {
  59276. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59277. if (vb) {
  59278. vb._rebuild();
  59279. }
  59280. this._createIndexBuffer();
  59281. };
  59282. BoundingBoxRenderer.prototype.reset = function () {
  59283. this.renderList.reset();
  59284. };
  59285. BoundingBoxRenderer.prototype.render = function () {
  59286. if (this.renderList.length === 0) {
  59287. return;
  59288. }
  59289. this._prepareRessources();
  59290. if (!this._colorShader.isReady()) {
  59291. return;
  59292. }
  59293. var engine = this.scene.getEngine();
  59294. engine.setDepthWrite(false);
  59295. this._colorShader._preBind();
  59296. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59297. var boundingBox = this.renderList.data[boundingBoxIndex];
  59298. var min = boundingBox.minimum;
  59299. var max = boundingBox.maximum;
  59300. var diff = max.subtract(min);
  59301. var median = min.add(diff.scale(0.5));
  59302. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59303. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59304. .multiply(boundingBox.getWorldMatrix());
  59305. // VBOs
  59306. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59307. if (this.showBackLines) {
  59308. // Back
  59309. engine.setDepthFunctionToGreaterOrEqual();
  59310. this.scene.resetCachedMaterial();
  59311. this._colorShader.setColor4("color", this.backColor.toColor4());
  59312. this._colorShader.bind(worldMatrix);
  59313. // Draw order
  59314. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59315. }
  59316. // Front
  59317. engine.setDepthFunctionToLess();
  59318. this.scene.resetCachedMaterial();
  59319. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59320. this._colorShader.bind(worldMatrix);
  59321. // Draw order
  59322. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59323. }
  59324. this._colorShader.unbind();
  59325. engine.setDepthFunctionToLessOrEqual();
  59326. engine.setDepthWrite(true);
  59327. };
  59328. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  59329. this._prepareRessources();
  59330. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  59331. return;
  59332. }
  59333. var engine = this.scene.getEngine();
  59334. engine.setDepthWrite(false);
  59335. engine.setColorWrite(false);
  59336. this._colorShader._preBind();
  59337. var boundingBox = mesh._boundingInfo.boundingBox;
  59338. var min = boundingBox.minimum;
  59339. var max = boundingBox.maximum;
  59340. var diff = max.subtract(min);
  59341. var median = min.add(diff.scale(0.5));
  59342. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59343. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59344. .multiply(boundingBox.getWorldMatrix());
  59345. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59346. engine.setDepthFunctionToLess();
  59347. this.scene.resetCachedMaterial();
  59348. this._colorShader.bind(worldMatrix);
  59349. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59350. this._colorShader.unbind();
  59351. engine.setDepthFunctionToLessOrEqual();
  59352. engine.setDepthWrite(true);
  59353. engine.setColorWrite(true);
  59354. };
  59355. BoundingBoxRenderer.prototype.dispose = function () {
  59356. if (!this._colorShader) {
  59357. return;
  59358. }
  59359. this.renderList.dispose();
  59360. this._colorShader.dispose();
  59361. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59362. if (buffer) {
  59363. buffer.dispose();
  59364. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59365. }
  59366. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  59367. };
  59368. return BoundingBoxRenderer;
  59369. }());
  59370. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59371. })(BABYLON || (BABYLON = {}));
  59372. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59373. var BABYLON;
  59374. (function (BABYLON) {
  59375. BABYLON.Engine.prototype.createTransformFeedback = function () {
  59376. return this._gl.createTransformFeedback();
  59377. };
  59378. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  59379. this._gl.deleteTransformFeedback(value);
  59380. };
  59381. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  59382. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  59383. };
  59384. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  59385. if (usePoints === void 0) { usePoints = true; }
  59386. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  59387. };
  59388. BABYLON.Engine.prototype.endTransformFeedback = function () {
  59389. this._gl.endTransformFeedback();
  59390. };
  59391. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  59392. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  59393. };
  59394. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  59395. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  59396. };
  59397. })(BABYLON || (BABYLON = {}));
  59398. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  59399. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59400. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59401. s = arguments[i];
  59402. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59403. t[p] = s[p];
  59404. }
  59405. return t;
  59406. };
  59407. var BABYLON;
  59408. (function (BABYLON) {
  59409. /**
  59410. * This represents a GPU particle system in Babylon
  59411. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  59412. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  59413. */
  59414. var GPUParticleSystem = /** @class */ (function () {
  59415. /**
  59416. * Instantiates a GPU particle system.
  59417. * 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.
  59418. * @param name The name of the particle system
  59419. * @param options The options used to create the system
  59420. * @param scene The scene the particle system belongs to
  59421. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59422. */
  59423. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  59424. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59425. /**
  59426. * The emitter represents the Mesh or position we are attaching the particle system to.
  59427. */
  59428. this.emitter = null;
  59429. /**
  59430. * The rendering group used by the Particle system to chose when to render.
  59431. */
  59432. this.renderingGroupId = 0;
  59433. /**
  59434. * The layer mask we are rendering the particles through.
  59435. */
  59436. this.layerMask = 0x0FFFFFFF;
  59437. this._accumulatedCount = 0;
  59438. this._targetIndex = 0;
  59439. this._currentRenderId = -1;
  59440. this._started = false;
  59441. this._stopped = false;
  59442. this._timeDelta = 0;
  59443. this._attributesStrideSize = 21;
  59444. this._actualFrame = 0;
  59445. this._rawTextureWidth = 256;
  59446. /**
  59447. * List of animations used by the particle system.
  59448. */
  59449. this.animations = [];
  59450. /**
  59451. * An event triggered when the system is disposed.
  59452. */
  59453. this.onDisposeObservable = new BABYLON.Observable();
  59454. /**
  59455. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59456. */
  59457. this.updateSpeed = 0.01;
  59458. /**
  59459. * The amount of time the particle system is running (depends of the overall update speed).
  59460. */
  59461. this.targetStopDuration = 0;
  59462. /**
  59463. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59464. */
  59465. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59466. /**
  59467. * Minimum life time of emitting particles.
  59468. */
  59469. this.minLifeTime = 1;
  59470. /**
  59471. * Maximum life time of emitting particles.
  59472. */
  59473. this.maxLifeTime = 1;
  59474. /**
  59475. * Minimum Size of emitting particles.
  59476. */
  59477. this.minSize = 1;
  59478. /**
  59479. * Maximum Size of emitting particles.
  59480. */
  59481. this.maxSize = 1;
  59482. /**
  59483. * Minimum scale of emitting particles on X axis.
  59484. */
  59485. this.minScaleX = 1;
  59486. /**
  59487. * Maximum scale of emitting particles on X axis.
  59488. */
  59489. this.maxScaleX = 1;
  59490. /**
  59491. * Minimum scale of emitting particles on Y axis.
  59492. */
  59493. this.minScaleY = 1;
  59494. /**
  59495. * Maximum scale of emitting particles on Y axis.
  59496. */
  59497. this.maxScaleY = 1;
  59498. /**
  59499. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59500. */
  59501. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59502. /**
  59503. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59504. */
  59505. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59506. /**
  59507. * Color the particle will have at the end of its lifetime.
  59508. */
  59509. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  59510. /**
  59511. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  59512. */
  59513. this.emitRate = 100;
  59514. /**
  59515. * You can use gravity if you want to give an orientation to your particles.
  59516. */
  59517. this.gravity = BABYLON.Vector3.Zero();
  59518. /**
  59519. * Minimum power of emitting particles.
  59520. */
  59521. this.minEmitPower = 1;
  59522. /**
  59523. * Maximum power of emitting particles.
  59524. */
  59525. this.maxEmitPower = 1;
  59526. /**
  59527. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59528. */
  59529. this.minAngularSpeed = 0;
  59530. /**
  59531. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59532. */
  59533. this.maxAngularSpeed = 0;
  59534. /**
  59535. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59536. * to override the particles.
  59537. */
  59538. this.forceDepthWrite = false;
  59539. this._preWarmDone = false;
  59540. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  59541. this.preWarmCycles = 0;
  59542. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59543. this.preWarmStepOffset = 1;
  59544. /**
  59545. * Gets or sets the minimal initial rotation in radians.
  59546. */
  59547. this.minInitialRotation = 0;
  59548. /**
  59549. * Gets or sets the maximal initial rotation in radians.
  59550. */
  59551. this.maxInitialRotation = 0;
  59552. /**
  59553. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  59554. */
  59555. this.spriteCellChangeSpeed = 1;
  59556. /**
  59557. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59558. */
  59559. this.startSpriteCellID = 0;
  59560. /**
  59561. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59562. */
  59563. this.endSpriteCellID = 0;
  59564. /**
  59565. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59566. */
  59567. this.spriteCellWidth = 0;
  59568. /**
  59569. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59570. */
  59571. this.spriteCellHeight = 0;
  59572. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59573. this.translationPivot = new BABYLON.Vector2(0, 0);
  59574. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59575. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59576. /**
  59577. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59578. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  59579. */
  59580. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59581. this._isBillboardBased = true;
  59582. this._colorGradients = null;
  59583. this._angularSpeedGradients = null;
  59584. this._sizeGradients = null;
  59585. this._velocityGradients = null;
  59586. this.id = name;
  59587. this.name = name;
  59588. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59589. this._engine = this._scene.getEngine();
  59590. if (!options.randomTextureSize) {
  59591. delete options.randomTextureSize;
  59592. }
  59593. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  59594. var optionsAsNumber = options;
  59595. if (isFinite(optionsAsNumber)) {
  59596. fullOptions.capacity = optionsAsNumber;
  59597. }
  59598. this._capacity = fullOptions.capacity;
  59599. this._activeCount = fullOptions.capacity;
  59600. this._currentActiveCount = 0;
  59601. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59602. this._scene.particleSystems.push(this);
  59603. this._updateEffectOptions = {
  59604. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  59605. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  59606. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  59607. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  59608. uniformBuffersNames: [],
  59609. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  59610. defines: "",
  59611. fallbacks: null,
  59612. onCompiled: null,
  59613. onError: null,
  59614. indexParameters: null,
  59615. maxSimultaneousLights: 0,
  59616. transformFeedbackVaryings: []
  59617. };
  59618. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59619. // Random data
  59620. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  59621. var d = [];
  59622. for (var i = 0; i < maxTextureSize; ++i) {
  59623. d.push(Math.random());
  59624. d.push(Math.random());
  59625. d.push(Math.random());
  59626. d.push(Math.random());
  59627. }
  59628. 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);
  59629. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59630. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59631. d = [];
  59632. for (var i = 0; i < maxTextureSize; ++i) {
  59633. d.push(Math.random());
  59634. d.push(Math.random());
  59635. d.push(Math.random());
  59636. d.push(Math.random());
  59637. }
  59638. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  59639. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59640. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59641. this._randomTextureSize = maxTextureSize;
  59642. }
  59643. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  59644. /**
  59645. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  59646. */
  59647. get: function () {
  59648. if (!BABYLON.Engine.LastCreatedEngine) {
  59649. return false;
  59650. }
  59651. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  59652. },
  59653. enumerable: true,
  59654. configurable: true
  59655. });
  59656. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  59657. /**
  59658. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59659. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59660. */
  59661. get: function () {
  59662. if (this.particleEmitterType.direction1) {
  59663. return this.particleEmitterType.direction1;
  59664. }
  59665. return BABYLON.Vector3.Zero();
  59666. },
  59667. set: function (value) {
  59668. if (this.particleEmitterType.direction1) {
  59669. this.particleEmitterType.direction1 = value;
  59670. }
  59671. },
  59672. enumerable: true,
  59673. configurable: true
  59674. });
  59675. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  59676. /**
  59677. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59678. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59679. */
  59680. get: function () {
  59681. if (this.particleEmitterType.direction2) {
  59682. return this.particleEmitterType.direction2;
  59683. }
  59684. return BABYLON.Vector3.Zero();
  59685. },
  59686. set: function (value) {
  59687. if (this.particleEmitterType.direction2) {
  59688. this.particleEmitterType.direction2 = value;
  59689. }
  59690. },
  59691. enumerable: true,
  59692. configurable: true
  59693. });
  59694. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  59695. /**
  59696. * 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.
  59697. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59698. */
  59699. get: function () {
  59700. if (this.particleEmitterType.minEmitBox) {
  59701. return this.particleEmitterType.minEmitBox;
  59702. }
  59703. return BABYLON.Vector3.Zero();
  59704. },
  59705. set: function (value) {
  59706. if (this.particleEmitterType.minEmitBox) {
  59707. this.particleEmitterType.minEmitBox = value;
  59708. }
  59709. },
  59710. enumerable: true,
  59711. configurable: true
  59712. });
  59713. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  59714. /**
  59715. * 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.
  59716. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59717. */
  59718. get: function () {
  59719. if (this.particleEmitterType.maxEmitBox) {
  59720. return this.particleEmitterType.maxEmitBox;
  59721. }
  59722. return BABYLON.Vector3.Zero();
  59723. },
  59724. set: function (value) {
  59725. if (this.particleEmitterType.maxEmitBox) {
  59726. this.particleEmitterType.maxEmitBox = value;
  59727. }
  59728. },
  59729. enumerable: true,
  59730. configurable: true
  59731. });
  59732. /**
  59733. * Gets the maximum number of particles active at the same time.
  59734. * @returns The max number of active particles.
  59735. */
  59736. GPUParticleSystem.prototype.getCapacity = function () {
  59737. return this._capacity;
  59738. };
  59739. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  59740. /**
  59741. * Gets or set the number of active particles
  59742. */
  59743. get: function () {
  59744. return this._activeCount;
  59745. },
  59746. set: function (value) {
  59747. this._activeCount = Math.min(value, this._capacity);
  59748. },
  59749. enumerable: true,
  59750. configurable: true
  59751. });
  59752. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  59753. /**
  59754. * Gets whether an animation sprite sheet is enabled or not on the particle system
  59755. */
  59756. get: function () {
  59757. return this._isAnimationSheetEnabled;
  59758. },
  59759. enumerable: true,
  59760. configurable: true
  59761. });
  59762. /**
  59763. * Is this system ready to be used/rendered
  59764. * @return true if the system is ready
  59765. */
  59766. GPUParticleSystem.prototype.isReady = function () {
  59767. if (!this._updateEffect) {
  59768. this._recreateUpdateEffect();
  59769. this._recreateRenderEffect();
  59770. return false;
  59771. }
  59772. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59773. return false;
  59774. }
  59775. return true;
  59776. };
  59777. /**
  59778. * Gets Wether the system has been started.
  59779. * @returns True if it has been started, otherwise false.
  59780. */
  59781. GPUParticleSystem.prototype.isStarted = function () {
  59782. return this._started;
  59783. };
  59784. /**
  59785. * Starts the particle system and begins to emit
  59786. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  59787. */
  59788. GPUParticleSystem.prototype.start = function (delay) {
  59789. var _this = this;
  59790. if (delay === void 0) { delay = 0; }
  59791. if (delay) {
  59792. setTimeout(function () {
  59793. _this.start(0);
  59794. }, delay);
  59795. return;
  59796. }
  59797. this._started = true;
  59798. this._stopped = false;
  59799. this._preWarmDone = false;
  59800. };
  59801. /**
  59802. * Stops the particle system.
  59803. */
  59804. GPUParticleSystem.prototype.stop = function () {
  59805. this._stopped = true;
  59806. };
  59807. /**
  59808. * Remove all active particles
  59809. */
  59810. GPUParticleSystem.prototype.reset = function () {
  59811. this._releaseBuffers();
  59812. this._releaseVAOs();
  59813. this._currentActiveCount = 0;
  59814. this._targetIndex = 0;
  59815. };
  59816. /**
  59817. * Returns the string "GPUParticleSystem"
  59818. * @returns a string containing the class name
  59819. */
  59820. GPUParticleSystem.prototype.getClassName = function () {
  59821. return "GPUParticleSystem";
  59822. };
  59823. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  59824. /**
  59825. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  59826. */
  59827. get: function () {
  59828. return this._isBillboardBased;
  59829. },
  59830. set: function (value) {
  59831. if (this._isBillboardBased === value) {
  59832. return;
  59833. }
  59834. this._isBillboardBased = value;
  59835. this._releaseBuffers();
  59836. },
  59837. enumerable: true,
  59838. configurable: true
  59839. });
  59840. /**
  59841. * Gets the current list of color gradients.
  59842. * You must use addColorGradient and removeColorGradient to udpate this list
  59843. * @returns the list of color gradients
  59844. */
  59845. GPUParticleSystem.prototype.getColorGradients = function () {
  59846. return this._colorGradients;
  59847. };
  59848. /**
  59849. * Gets the current list of size gradients.
  59850. * You must use addSizeGradient and removeSizeGradient to udpate this list
  59851. * @returns the list of size gradients
  59852. */
  59853. GPUParticleSystem.prototype.getSizeGradients = function () {
  59854. return this._sizeGradients;
  59855. };
  59856. /**
  59857. * Gets the current list of angular speed gradients.
  59858. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  59859. * @returns the list of angular speed gradients
  59860. */
  59861. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  59862. return this._angularSpeedGradients;
  59863. };
  59864. /**
  59865. * Gets the current list of velocity gradients.
  59866. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  59867. * @returns the list of angular speed gradients
  59868. */
  59869. GPUParticleSystem.prototype.getVelocityGradients = function () {
  59870. return this._velocityGradients;
  59871. };
  59872. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  59873. if (!gradients) {
  59874. return this;
  59875. }
  59876. var index = 0;
  59877. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59878. var valueGradient = gradients_1[_i];
  59879. if (valueGradient.gradient === gradient) {
  59880. gradients.splice(index, 1);
  59881. break;
  59882. }
  59883. index++;
  59884. }
  59885. if (texture) {
  59886. texture.dispose();
  59887. }
  59888. this._releaseBuffers();
  59889. return this;
  59890. };
  59891. /**
  59892. * Adds a new color gradient
  59893. * @param gradient defines the gradient to use (between 0 and 1)
  59894. * @param color defines the color to affect to the specified gradient
  59895. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59896. * @returns the current particle system
  59897. */
  59898. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59899. if (!this._colorGradients) {
  59900. this._colorGradients = [];
  59901. }
  59902. var colorGradient = new BABYLON.ColorGradient();
  59903. colorGradient.gradient = gradient;
  59904. colorGradient.color1 = color1;
  59905. this._colorGradients.push(colorGradient);
  59906. this._colorGradients.sort(function (a, b) {
  59907. if (a.gradient < b.gradient) {
  59908. return -1;
  59909. }
  59910. else if (a.gradient > b.gradient) {
  59911. return 1;
  59912. }
  59913. return 0;
  59914. });
  59915. if (this._colorGradientsTexture) {
  59916. this._colorGradientsTexture.dispose();
  59917. this._colorGradientsTexture = null;
  59918. }
  59919. this._releaseBuffers();
  59920. return this;
  59921. };
  59922. /**
  59923. * Remove a specific color gradient
  59924. * @param gradient defines the gradient to remove
  59925. * @returns the current particle system
  59926. */
  59927. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  59928. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  59929. this._colorGradientsTexture = null;
  59930. return this;
  59931. };
  59932. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  59933. var valueGradient = new BABYLON.FactorGradient();
  59934. valueGradient.gradient = gradient;
  59935. valueGradient.factor1 = factor;
  59936. factorGradients.push(valueGradient);
  59937. factorGradients.sort(function (a, b) {
  59938. if (a.gradient < b.gradient) {
  59939. return -1;
  59940. }
  59941. else if (a.gradient > b.gradient) {
  59942. return 1;
  59943. }
  59944. return 0;
  59945. });
  59946. this._releaseBuffers();
  59947. };
  59948. /**
  59949. * Adds a new size gradient
  59950. * @param gradient defines the gradient to use (between 0 and 1)
  59951. * @param factor defines the size factor to affect to the specified gradient
  59952. * @returns the current particle system
  59953. */
  59954. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  59955. if (!this._sizeGradients) {
  59956. this._sizeGradients = [];
  59957. }
  59958. this._addFactorGradient(this._sizeGradients, gradient, factor);
  59959. if (this._sizeGradientsTexture) {
  59960. this._sizeGradientsTexture.dispose();
  59961. this._sizeGradientsTexture = null;
  59962. }
  59963. this._releaseBuffers();
  59964. return this;
  59965. };
  59966. /**
  59967. * Remove a specific size gradient
  59968. * @param gradient defines the gradient to remove
  59969. * @returns the current particle system
  59970. */
  59971. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59972. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  59973. this._sizeGradientsTexture = null;
  59974. return this;
  59975. };
  59976. /**
  59977. * Adds a new angular speed gradient
  59978. * @param gradient defines the gradient to use (between 0 and 1)
  59979. * @param factor defines the size factor to affect to the specified gradient
  59980. * @returns the current particle system
  59981. */
  59982. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  59983. if (!this._angularSpeedGradients) {
  59984. this._angularSpeedGradients = [];
  59985. }
  59986. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  59987. if (this._angularSpeedGradientsTexture) {
  59988. this._angularSpeedGradientsTexture.dispose();
  59989. this._angularSpeedGradientsTexture = null;
  59990. }
  59991. this._releaseBuffers();
  59992. return this;
  59993. };
  59994. /**
  59995. * Remove a specific angular speed gradient
  59996. * @param gradient defines the gradient to remove
  59997. * @returns the current particle system
  59998. */
  59999. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60000. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  60001. this._angularSpeedGradientsTexture = null;
  60002. return this;
  60003. };
  60004. /**
  60005. * Adds a new velocity gradient
  60006. * @param gradient defines the gradient to use (between 0 and 1)
  60007. * @param factor defines the size factor to affect to the specified gradient
  60008. * @returns the current particle system
  60009. */
  60010. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  60011. if (!this._velocityGradients) {
  60012. this._velocityGradients = [];
  60013. }
  60014. this._addFactorGradient(this._velocityGradients, gradient, factor);
  60015. if (this._velocityGradientsTexture) {
  60016. this._velocityGradientsTexture.dispose();
  60017. this._velocityGradientsTexture = null;
  60018. }
  60019. this._releaseBuffers();
  60020. return this;
  60021. };
  60022. /**
  60023. * Remove a specific velocity gradient
  60024. * @param gradient defines the gradient to remove
  60025. * @returns the current particle system
  60026. */
  60027. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60028. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60029. this._velocityGradientsTexture = null;
  60030. return this;
  60031. };
  60032. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60033. var updateVertexBuffers = {};
  60034. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60035. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60036. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60037. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60038. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60039. var offset = 12;
  60040. if (!this._colorGradientsTexture) {
  60041. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60042. offset += 4;
  60043. }
  60044. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60045. offset += 3;
  60046. if (!this._isBillboardBased) {
  60047. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60048. offset += 3;
  60049. }
  60050. if (this._angularSpeedGradientsTexture) {
  60051. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60052. offset += 1;
  60053. }
  60054. else {
  60055. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60056. offset += 2;
  60057. }
  60058. if (this._isAnimationSheetEnabled) {
  60059. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60060. offset += 1;
  60061. }
  60062. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60063. this._engine.bindArrayBuffer(null);
  60064. return vao;
  60065. };
  60066. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60067. var renderVertexBuffers = {};
  60068. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60069. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60070. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60071. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60072. var offset = 12;
  60073. if (!this._colorGradientsTexture) {
  60074. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60075. offset += 4;
  60076. }
  60077. offset += 3; // Direction
  60078. if (!this._isBillboardBased) {
  60079. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60080. offset += 3;
  60081. }
  60082. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60083. if (this._angularSpeedGradientsTexture) {
  60084. offset++;
  60085. }
  60086. else {
  60087. offset += 2;
  60088. }
  60089. if (this._isAnimationSheetEnabled) {
  60090. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60091. offset += 1;
  60092. }
  60093. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60094. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60095. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60096. this._engine.bindArrayBuffer(null);
  60097. return vao;
  60098. };
  60099. GPUParticleSystem.prototype._initialize = function (force) {
  60100. if (force === void 0) { force = false; }
  60101. if (this._buffer0 && !force) {
  60102. return;
  60103. }
  60104. var engine = this._scene.getEngine();
  60105. var data = new Array();
  60106. if (!this.isBillboardBased) {
  60107. this._attributesStrideSize += 3;
  60108. }
  60109. if (this._colorGradientsTexture) {
  60110. this._attributesStrideSize -= 4;
  60111. }
  60112. if (this._angularSpeedGradientsTexture) {
  60113. this._attributesStrideSize -= 1;
  60114. }
  60115. if (this._isAnimationSheetEnabled) {
  60116. this._attributesStrideSize += 1;
  60117. }
  60118. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60119. // position
  60120. data.push(0.0);
  60121. data.push(0.0);
  60122. data.push(0.0);
  60123. // Age and life
  60124. data.push(0.0); // create the particle as a dead one to create a new one at start
  60125. data.push(0.0);
  60126. // Seed
  60127. data.push(Math.random());
  60128. data.push(Math.random());
  60129. data.push(Math.random());
  60130. data.push(Math.random());
  60131. // Size
  60132. data.push(0.0);
  60133. data.push(0.0);
  60134. data.push(0.0);
  60135. if (!this._colorGradientsTexture) {
  60136. // color
  60137. data.push(0.0);
  60138. data.push(0.0);
  60139. data.push(0.0);
  60140. data.push(0.0);
  60141. }
  60142. // direction
  60143. data.push(0.0);
  60144. data.push(0.0);
  60145. data.push(0.0);
  60146. if (!this.isBillboardBased) {
  60147. // initialDirection
  60148. data.push(0.0);
  60149. data.push(0.0);
  60150. data.push(0.0);
  60151. }
  60152. // angle
  60153. data.push(0.0);
  60154. if (!this._angularSpeedGradientsTexture) {
  60155. data.push(0.0);
  60156. }
  60157. if (this._isAnimationSheetEnabled) {
  60158. data.push(0.0);
  60159. }
  60160. }
  60161. // Sprite data
  60162. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  60163. -0.5, 0.5, 0, 1,
  60164. -0.5, -0.5, 0, 0,
  60165. 0.5, -0.5, 1, 0]);
  60166. // Buffers
  60167. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60168. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60169. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  60170. // Update VAO
  60171. this._updateVAO = [];
  60172. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  60173. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  60174. // Render VAO
  60175. this._renderVAO = [];
  60176. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  60177. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  60178. // Links
  60179. this._sourceBuffer = this._buffer0;
  60180. this._targetBuffer = this._buffer1;
  60181. };
  60182. /** @hidden */
  60183. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  60184. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  60185. if (this._isBillboardBased) {
  60186. defines += "\n#define BILLBOARD";
  60187. }
  60188. if (this._colorGradientsTexture) {
  60189. defines += "\n#define COLORGRADIENTS";
  60190. }
  60191. if (this._sizeGradientsTexture) {
  60192. defines += "\n#define SIZEGRADIENTS";
  60193. }
  60194. if (this._angularSpeedGradientsTexture) {
  60195. defines += "\n#define ANGULARSPEEDGRADIENTS";
  60196. }
  60197. if (this._velocityGradientsTexture) {
  60198. defines += "\n#define VELOCITYGRADIENTS";
  60199. }
  60200. if (this.isAnimationSheetEnabled) {
  60201. defines += "\n#define ANIMATESHEET";
  60202. }
  60203. if (this.noiseTexture) {
  60204. defines += "\n#define NOISE";
  60205. }
  60206. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  60207. return;
  60208. }
  60209. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  60210. if (!this._colorGradientsTexture) {
  60211. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  60212. }
  60213. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  60214. if (!this._isBillboardBased) {
  60215. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  60216. }
  60217. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  60218. if (this.isAnimationSheetEnabled) {
  60219. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  60220. }
  60221. this._updateEffectOptions.defines = defines;
  60222. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  60223. };
  60224. /** @hidden */
  60225. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  60226. var defines = "";
  60227. if (this._scene.clipPlane) {
  60228. defines = "\n#define CLIPPLANE";
  60229. }
  60230. if (this._isBillboardBased) {
  60231. defines += "\n#define BILLBOARD";
  60232. switch (this.billboardMode) {
  60233. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  60234. defines += "\n#define BILLBOARDY";
  60235. break;
  60236. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  60237. default:
  60238. break;
  60239. }
  60240. }
  60241. if (this._colorGradientsTexture) {
  60242. defines += "\n#define COLORGRADIENTS";
  60243. }
  60244. if (this.isAnimationSheetEnabled) {
  60245. defines += "\n#define ANIMATESHEET";
  60246. }
  60247. if (this._renderEffect && this._renderEffect.defines === defines) {
  60248. return;
  60249. }
  60250. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  60251. };
  60252. /**
  60253. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60254. * @param preWarm defines if we are in the pre-warmimg phase
  60255. */
  60256. GPUParticleSystem.prototype.animate = function (preWarm) {
  60257. if (preWarm === void 0) { preWarm = false; }
  60258. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60259. this._actualFrame += this._timeDelta;
  60260. if (!this._stopped) {
  60261. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60262. this.stop();
  60263. }
  60264. }
  60265. };
  60266. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  60267. var texture = this[textureName];
  60268. if (!factorGradients || !factorGradients.length || texture) {
  60269. return;
  60270. }
  60271. var data = new Float32Array(this._rawTextureWidth);
  60272. for (var x = 0; x < this._rawTextureWidth; x++) {
  60273. var ratio = x / this._rawTextureWidth;
  60274. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  60275. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60276. });
  60277. }
  60278. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60279. };
  60280. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  60281. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  60282. };
  60283. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  60284. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  60285. };
  60286. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  60287. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  60288. };
  60289. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  60290. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  60291. return;
  60292. }
  60293. var data = new Uint8Array(this._rawTextureWidth * 4);
  60294. var tmpColor = BABYLON.Tmp.Color4[0];
  60295. for (var x = 0; x < this._rawTextureWidth; x++) {
  60296. var ratio = x / this._rawTextureWidth;
  60297. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  60298. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  60299. data[x * 4] = tmpColor.r * 255;
  60300. data[x * 4 + 1] = tmpColor.g * 255;
  60301. data[x * 4 + 2] = tmpColor.b * 255;
  60302. data[x * 4 + 3] = tmpColor.a * 255;
  60303. });
  60304. }
  60305. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60306. };
  60307. /**
  60308. * Renders the particle system in its current state
  60309. * @param preWarm defines if the system should only update the particles but not render them
  60310. * @returns the current number of particles
  60311. */
  60312. GPUParticleSystem.prototype.render = function (preWarm) {
  60313. if (preWarm === void 0) { preWarm = false; }
  60314. if (!this._started) {
  60315. return 0;
  60316. }
  60317. this._createColorGradientTexture();
  60318. this._createSizeGradientTexture();
  60319. this._createAngularSpeedGradientTexture();
  60320. this._createVelocityGradientTexture();
  60321. this._recreateUpdateEffect();
  60322. this._recreateRenderEffect();
  60323. if (!this.isReady()) {
  60324. return 0;
  60325. }
  60326. if (!preWarm) {
  60327. if (!this._preWarmDone && this.preWarmCycles) {
  60328. for (var index = 0; index < this.preWarmCycles; index++) {
  60329. this.animate(true);
  60330. this.render(true);
  60331. }
  60332. this._preWarmDone = true;
  60333. }
  60334. if (this._currentRenderId === this._scene.getRenderId()) {
  60335. return 0;
  60336. }
  60337. this._currentRenderId = this._scene.getRenderId();
  60338. }
  60339. // Get everything ready to render
  60340. this._initialize();
  60341. this._accumulatedCount += this.emitRate * this._timeDelta;
  60342. if (this._accumulatedCount > 1) {
  60343. var intPart = this._accumulatedCount | 0;
  60344. this._accumulatedCount -= intPart;
  60345. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60346. }
  60347. if (!this._currentActiveCount) {
  60348. return 0;
  60349. }
  60350. // Enable update effect
  60351. this._engine.enableEffect(this._updateEffect);
  60352. this._engine.setState(false);
  60353. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60354. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60355. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60356. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60357. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60358. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  60359. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  60360. if (!this._colorGradientsTexture) {
  60361. this._updateEffect.setDirectColor4("color1", this.color1);
  60362. this._updateEffect.setDirectColor4("color2", this.color2);
  60363. }
  60364. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  60365. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  60366. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  60367. this._updateEffect.setVector3("gravity", this.gravity);
  60368. if (this._sizeGradientsTexture) {
  60369. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  60370. }
  60371. if (this._angularSpeedGradientsTexture) {
  60372. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  60373. }
  60374. if (this._velocityGradientsTexture) {
  60375. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  60376. }
  60377. if (this.particleEmitterType) {
  60378. this.particleEmitterType.applyToShader(this._updateEffect);
  60379. }
  60380. if (this._isAnimationSheetEnabled) {
  60381. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  60382. }
  60383. if (this.noiseTexture) {
  60384. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  60385. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  60386. }
  60387. var emitterWM;
  60388. if (this.emitter.position) {
  60389. var emitterMesh = this.emitter;
  60390. emitterWM = emitterMesh.getWorldMatrix();
  60391. }
  60392. else {
  60393. var emitterPosition = this.emitter;
  60394. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60395. }
  60396. this._updateEffect.setMatrix("emitterWM", emitterWM);
  60397. // Bind source VAO
  60398. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  60399. // Update
  60400. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  60401. this._engine.setRasterizerState(false);
  60402. this._engine.beginTransformFeedback(true);
  60403. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  60404. this._engine.endTransformFeedback();
  60405. this._engine.setRasterizerState(true);
  60406. this._engine.bindTransformFeedbackBuffer(null);
  60407. if (!preWarm) {
  60408. // Enable render effect
  60409. this._engine.enableEffect(this._renderEffect);
  60410. var viewMatrix = this._scene.getViewMatrix();
  60411. this._renderEffect.setMatrix("view", viewMatrix);
  60412. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  60413. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  60414. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  60415. if (this._colorGradientsTexture) {
  60416. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  60417. }
  60418. else {
  60419. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  60420. }
  60421. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60422. var baseSize = this.particleTexture.getBaseSize();
  60423. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60424. }
  60425. if (this._isBillboardBased) {
  60426. var camera = this._scene.activeCamera;
  60427. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60428. }
  60429. if (this._scene.clipPlane) {
  60430. var clipPlane = this._scene.clipPlane;
  60431. var invView = viewMatrix.clone();
  60432. invView.invert();
  60433. this._renderEffect.setMatrix("invView", invView);
  60434. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60435. }
  60436. // Draw order
  60437. switch (this.blendMode) {
  60438. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60439. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60440. break;
  60441. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60442. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60443. break;
  60444. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60445. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60446. break;
  60447. }
  60448. if (this.forceDepthWrite) {
  60449. this._engine.setDepthWrite(true);
  60450. }
  60451. // Bind source VAO
  60452. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60453. // Render
  60454. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60455. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60456. }
  60457. // Switch VAOs
  60458. this._targetIndex++;
  60459. if (this._targetIndex === 2) {
  60460. this._targetIndex = 0;
  60461. }
  60462. // Switch buffers
  60463. var tmpBuffer = this._sourceBuffer;
  60464. this._sourceBuffer = this._targetBuffer;
  60465. this._targetBuffer = tmpBuffer;
  60466. return this._currentActiveCount;
  60467. };
  60468. /**
  60469. * Rebuilds the particle system
  60470. */
  60471. GPUParticleSystem.prototype.rebuild = function () {
  60472. this._initialize(true);
  60473. };
  60474. GPUParticleSystem.prototype._releaseBuffers = function () {
  60475. if (this._buffer0) {
  60476. this._buffer0.dispose();
  60477. this._buffer0 = null;
  60478. }
  60479. if (this._buffer1) {
  60480. this._buffer1.dispose();
  60481. this._buffer1 = null;
  60482. }
  60483. if (this._spriteBuffer) {
  60484. this._spriteBuffer.dispose();
  60485. this._spriteBuffer = null;
  60486. }
  60487. };
  60488. GPUParticleSystem.prototype._releaseVAOs = function () {
  60489. if (!this._updateVAO) {
  60490. return;
  60491. }
  60492. for (var index = 0; index < this._updateVAO.length; index++) {
  60493. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60494. }
  60495. this._updateVAO = [];
  60496. for (var index = 0; index < this._renderVAO.length; index++) {
  60497. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60498. }
  60499. this._renderVAO = [];
  60500. };
  60501. /**
  60502. * Disposes the particle system and free the associated resources
  60503. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60504. */
  60505. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60506. if (disposeTexture === void 0) { disposeTexture = true; }
  60507. var index = this._scene.particleSystems.indexOf(this);
  60508. if (index > -1) {
  60509. this._scene.particleSystems.splice(index, 1);
  60510. }
  60511. this._releaseBuffers();
  60512. this._releaseVAOs();
  60513. if (this._colorGradientsTexture) {
  60514. this._colorGradientsTexture.dispose();
  60515. this._colorGradientsTexture = null;
  60516. }
  60517. if (this._sizeGradientsTexture) {
  60518. this._sizeGradientsTexture.dispose();
  60519. this._sizeGradientsTexture = null;
  60520. }
  60521. if (this._angularSpeedGradientsTexture) {
  60522. this._angularSpeedGradientsTexture.dispose();
  60523. this._angularSpeedGradientsTexture = null;
  60524. }
  60525. if (this._velocityGradientsTexture) {
  60526. this._velocityGradientsTexture.dispose();
  60527. this._velocityGradientsTexture = null;
  60528. }
  60529. if (this._randomTexture) {
  60530. this._randomTexture.dispose();
  60531. this._randomTexture = null;
  60532. }
  60533. if (this._randomTexture2) {
  60534. this._randomTexture2.dispose();
  60535. this._randomTexture2 = null;
  60536. }
  60537. if (disposeTexture && this.particleTexture) {
  60538. this.particleTexture.dispose();
  60539. this.particleTexture = null;
  60540. }
  60541. if (disposeTexture && this.noiseTexture) {
  60542. this.noiseTexture.dispose();
  60543. this.noiseTexture = null;
  60544. }
  60545. // Callback
  60546. this.onDisposeObservable.notifyObservers(this);
  60547. this.onDisposeObservable.clear();
  60548. };
  60549. /**
  60550. * Clones the particle system.
  60551. * @param name The name of the cloned object
  60552. * @param newEmitter The new emitter to use
  60553. * @returns the cloned particle system
  60554. */
  60555. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60556. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60557. BABYLON.Tools.DeepCopy(this, result);
  60558. if (newEmitter === undefined) {
  60559. newEmitter = this.emitter;
  60560. }
  60561. result.emitter = newEmitter;
  60562. if (this.particleTexture) {
  60563. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60564. }
  60565. return result;
  60566. };
  60567. /**
  60568. * Serializes the particle system to a JSON object.
  60569. * @returns the JSON object
  60570. */
  60571. GPUParticleSystem.prototype.serialize = function () {
  60572. var serializationObject = {};
  60573. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  60574. serializationObject.activeParticleCount = this.activeParticleCount;
  60575. return serializationObject;
  60576. };
  60577. /**
  60578. * Parses a JSON object to create a GPU particle system.
  60579. * @param parsedParticleSystem The JSON object to parse
  60580. * @param scene The scene to create the particle system in
  60581. * @param rootUrl The root url to use to load external dependencies like texture
  60582. * @returns the parsed GPU particle system
  60583. */
  60584. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  60585. var name = parsedParticleSystem.name;
  60586. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  60587. if (parsedParticleSystem.activeParticleCount) {
  60588. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  60589. }
  60590. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60591. return particleSystem;
  60592. };
  60593. return GPUParticleSystem;
  60594. }());
  60595. BABYLON.GPUParticleSystem = GPUParticleSystem;
  60596. })(BABYLON || (BABYLON = {}));
  60597. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  60598. var BABYLON;
  60599. (function (BABYLON) {
  60600. /**
  60601. * Represents one particle of a solid particle system.
  60602. */
  60603. var SolidParticle = /** @class */ (function () {
  60604. /**
  60605. * Creates a Solid Particle object.
  60606. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  60607. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  60608. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  60609. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  60610. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  60611. * @param shapeId (integer) is the model shape identifier in the SPS.
  60612. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  60613. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  60614. */
  60615. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  60616. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  60617. /**
  60618. * particle global index
  60619. */
  60620. this.idx = 0;
  60621. /**
  60622. * The color of the particle
  60623. */
  60624. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60625. /**
  60626. * The world space position of the particle.
  60627. */
  60628. this.position = BABYLON.Vector3.Zero();
  60629. /**
  60630. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  60631. */
  60632. this.rotation = BABYLON.Vector3.Zero();
  60633. /**
  60634. * The scaling of the particle.
  60635. */
  60636. this.scaling = BABYLON.Vector3.One();
  60637. /**
  60638. * The uvs of the particle.
  60639. */
  60640. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  60641. /**
  60642. * The current speed of the particle.
  60643. */
  60644. this.velocity = BABYLON.Vector3.Zero();
  60645. /**
  60646. * The pivot point in the particle local space.
  60647. */
  60648. this.pivot = BABYLON.Vector3.Zero();
  60649. /**
  60650. * Must the particle be translated from its pivot point in its local space ?
  60651. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  60652. * Default : false
  60653. */
  60654. this.translateFromPivot = false;
  60655. /**
  60656. * Is the particle active or not ?
  60657. */
  60658. this.alive = true;
  60659. /**
  60660. * Is the particle visible or not ?
  60661. */
  60662. this.isVisible = true;
  60663. /**
  60664. * Index of this particle in the global "positions" array (Internal use)
  60665. */
  60666. this._pos = 0;
  60667. /**
  60668. * Index of this particle in the global "indices" array (Internal use)
  60669. */
  60670. this._ind = 0;
  60671. /**
  60672. * ModelShape id of this particle
  60673. */
  60674. this.shapeId = 0;
  60675. /**
  60676. * Index of the particle in its shape id (Internal use)
  60677. */
  60678. this.idxInShape = 0;
  60679. /**
  60680. * Still set as invisible in order to skip useless computations (Internal use)
  60681. */
  60682. this._stillInvisible = false;
  60683. /**
  60684. * Last computed particle rotation matrix
  60685. */
  60686. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  60687. /**
  60688. * Parent particle Id, if any.
  60689. * Default null.
  60690. */
  60691. this.parentId = null;
  60692. /**
  60693. * Internal global position in the SPS.
  60694. */
  60695. this._globalPosition = BABYLON.Vector3.Zero();
  60696. this.idx = particleIndex;
  60697. this._pos = positionIndex;
  60698. this._ind = indiceIndex;
  60699. this._model = model;
  60700. this.shapeId = shapeId;
  60701. this.idxInShape = idxInShape;
  60702. this._sps = sps;
  60703. if (modelBoundingInfo) {
  60704. this._modelBoundingInfo = modelBoundingInfo;
  60705. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  60706. }
  60707. }
  60708. Object.defineProperty(SolidParticle.prototype, "scale", {
  60709. /**
  60710. * Legacy support, changed scale to scaling
  60711. */
  60712. get: function () {
  60713. return this.scaling;
  60714. },
  60715. /**
  60716. * Legacy support, changed scale to scaling
  60717. */
  60718. set: function (scale) {
  60719. this.scaling = scale;
  60720. },
  60721. enumerable: true,
  60722. configurable: true
  60723. });
  60724. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  60725. /**
  60726. * Legacy support, changed quaternion to rotationQuaternion
  60727. */
  60728. get: function () {
  60729. return this.rotationQuaternion;
  60730. },
  60731. /**
  60732. * Legacy support, changed quaternion to rotationQuaternion
  60733. */
  60734. set: function (q) {
  60735. this.rotationQuaternion = q;
  60736. },
  60737. enumerable: true,
  60738. configurable: true
  60739. });
  60740. /**
  60741. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  60742. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  60743. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  60744. * @returns true if it intersects
  60745. */
  60746. SolidParticle.prototype.intersectsMesh = function (target) {
  60747. if (!this._boundingInfo || !target._boundingInfo) {
  60748. return false;
  60749. }
  60750. if (this._sps._bSphereOnly) {
  60751. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  60752. }
  60753. return this._boundingInfo.intersects(target._boundingInfo, false);
  60754. };
  60755. return SolidParticle;
  60756. }());
  60757. BABYLON.SolidParticle = SolidParticle;
  60758. /**
  60759. * Represents the shape of the model used by one particle of a solid particle system.
  60760. * SPS internal tool, don't use it manually.
  60761. */
  60762. var ModelShape = /** @class */ (function () {
  60763. /**
  60764. * 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.
  60765. * SPS internal tool, don't use it manually.
  60766. * @hidden
  60767. */
  60768. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  60769. /**
  60770. * length of the shape in the model indices array (internal use)
  60771. */
  60772. this._indicesLength = 0;
  60773. this.shapeID = id;
  60774. this._shape = shape;
  60775. this._indicesLength = indicesLength;
  60776. this._shapeUV = shapeUV;
  60777. this._positionFunction = posFunction;
  60778. this._vertexFunction = vtxFunction;
  60779. }
  60780. return ModelShape;
  60781. }());
  60782. BABYLON.ModelShape = ModelShape;
  60783. /**
  60784. * Represents a Depth Sorted Particle in the solid particle system.
  60785. */
  60786. var DepthSortedParticle = /** @class */ (function () {
  60787. function DepthSortedParticle() {
  60788. /**
  60789. * Index of the particle in the "indices" array
  60790. */
  60791. this.ind = 0;
  60792. /**
  60793. * Length of the particle shape in the "indices" array
  60794. */
  60795. this.indicesLength = 0;
  60796. /**
  60797. * Squared distance from the particle to the camera
  60798. */
  60799. this.sqDistance = 0.0;
  60800. }
  60801. return DepthSortedParticle;
  60802. }());
  60803. BABYLON.DepthSortedParticle = DepthSortedParticle;
  60804. })(BABYLON || (BABYLON = {}));
  60805. //# sourceMappingURL=babylon.solidParticle.js.map
  60806. var BABYLON;
  60807. (function (BABYLON) {
  60808. /**
  60809. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  60810. *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.
  60811. * The SPS is also a particle system. It provides some methods to manage the particles.
  60812. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  60813. *
  60814. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  60815. */
  60816. var SolidParticleSystem = /** @class */ (function () {
  60817. /**
  60818. * Creates a SPS (Solid Particle System) object.
  60819. * @param name (String) is the SPS name, this will be the underlying mesh name.
  60820. * @param scene (Scene) is the scene in which the SPS is added.
  60821. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  60822. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  60823. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  60824. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  60825. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  60826. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  60827. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  60828. */
  60829. function SolidParticleSystem(name, scene, options) {
  60830. /**
  60831. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  60832. * Example : var p = SPS.particles[i];
  60833. */
  60834. this.particles = new Array();
  60835. /**
  60836. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  60837. */
  60838. this.nbParticles = 0;
  60839. /**
  60840. * If the particles must ever face the camera (default false). Useful for planar particles.
  60841. */
  60842. this.billboard = false;
  60843. /**
  60844. * Recompute normals when adding a shape
  60845. */
  60846. this.recomputeNormals = true;
  60847. /**
  60848. * This a counter ofr your own usage. It's not set by any SPS functions.
  60849. */
  60850. this.counter = 0;
  60851. /**
  60852. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  60853. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  60854. */
  60855. this.vars = {};
  60856. /**
  60857. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  60858. */
  60859. this._bSphereOnly = false;
  60860. /**
  60861. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  60862. */
  60863. this._bSphereRadiusFactor = 1.0;
  60864. this._positions = new Array();
  60865. this._indices = new Array();
  60866. this._normals = new Array();
  60867. this._colors = new Array();
  60868. this._uvs = new Array();
  60869. this._index = 0; // indices index
  60870. this._updatable = true;
  60871. this._pickable = false;
  60872. this._isVisibilityBoxLocked = false;
  60873. this._alwaysVisible = false;
  60874. this._depthSort = false;
  60875. this._shapeCounter = 0;
  60876. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  60877. this._color = new BABYLON.Color4(0, 0, 0, 0);
  60878. this._computeParticleColor = true;
  60879. this._computeParticleTexture = true;
  60880. this._computeParticleRotation = true;
  60881. this._computeParticleVertex = false;
  60882. this._computeBoundingBox = false;
  60883. this._depthSortParticles = true;
  60884. this._cam_axisZ = BABYLON.Vector3.Zero();
  60885. this._cam_axisY = BABYLON.Vector3.Zero();
  60886. this._cam_axisX = BABYLON.Vector3.Zero();
  60887. this._axisZ = BABYLON.Axis.Z;
  60888. this._camDir = BABYLON.Vector3.Zero();
  60889. this._camInvertedPosition = BABYLON.Vector3.Zero();
  60890. this._rotMatrix = new BABYLON.Matrix();
  60891. this._invertMatrix = new BABYLON.Matrix();
  60892. this._rotated = BABYLON.Vector3.Zero();
  60893. this._quaternion = new BABYLON.Quaternion();
  60894. this._vertex = BABYLON.Vector3.Zero();
  60895. this._normal = BABYLON.Vector3.Zero();
  60896. this._yaw = 0.0;
  60897. this._pitch = 0.0;
  60898. this._roll = 0.0;
  60899. this._halfroll = 0.0;
  60900. this._halfpitch = 0.0;
  60901. this._halfyaw = 0.0;
  60902. this._sinRoll = 0.0;
  60903. this._cosRoll = 0.0;
  60904. this._sinPitch = 0.0;
  60905. this._cosPitch = 0.0;
  60906. this._sinYaw = 0.0;
  60907. this._cosYaw = 0.0;
  60908. this._mustUnrotateFixedNormals = false;
  60909. this._minimum = BABYLON.Vector3.Zero();
  60910. this._maximum = BABYLON.Vector3.Zero();
  60911. this._minBbox = BABYLON.Vector3.Zero();
  60912. this._maxBbox = BABYLON.Vector3.Zero();
  60913. this._particlesIntersect = false;
  60914. this._depthSortFunction = function (p1, p2) {
  60915. return (p2.sqDistance - p1.sqDistance);
  60916. };
  60917. this._needs32Bits = false;
  60918. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  60919. this._scaledPivot = BABYLON.Vector3.Zero();
  60920. this._particleHasParent = false;
  60921. this.name = name;
  60922. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60923. this._camera = scene.activeCamera;
  60924. this._pickable = options ? options.isPickable : false;
  60925. this._depthSort = options ? options.enableDepthSort : false;
  60926. this._particlesIntersect = options ? options.particleIntersection : false;
  60927. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  60928. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  60929. if (options && options.updatable !== undefined) {
  60930. this._updatable = options.updatable;
  60931. }
  60932. else {
  60933. this._updatable = true;
  60934. }
  60935. if (this._pickable) {
  60936. this.pickedParticles = [];
  60937. }
  60938. if (this._depthSort) {
  60939. this.depthSortedParticles = [];
  60940. }
  60941. }
  60942. /**
  60943. * Builds the SPS underlying mesh. Returns a standard Mesh.
  60944. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  60945. * @returns the created mesh
  60946. */
  60947. SolidParticleSystem.prototype.buildMesh = function () {
  60948. if (this.nbParticles === 0) {
  60949. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  60950. this.addShape(triangle, 1);
  60951. triangle.dispose();
  60952. }
  60953. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  60954. this._positions32 = new Float32Array(this._positions);
  60955. this._uvs32 = new Float32Array(this._uvs);
  60956. this._colors32 = new Float32Array(this._colors);
  60957. if (this.recomputeNormals) {
  60958. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  60959. }
  60960. this._normals32 = new Float32Array(this._normals);
  60961. this._fixedNormal32 = new Float32Array(this._normals);
  60962. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  60963. this._unrotateFixedNormals();
  60964. }
  60965. var vertexData = new BABYLON.VertexData();
  60966. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  60967. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  60968. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  60969. if (this._uvs32.length > 0) {
  60970. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  60971. }
  60972. if (this._colors32.length > 0) {
  60973. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  60974. }
  60975. var mesh = new BABYLON.Mesh(this.name, this._scene);
  60976. vertexData.applyToMesh(mesh, this._updatable);
  60977. this.mesh = mesh;
  60978. this.mesh.isPickable = this._pickable;
  60979. // free memory
  60980. if (!this._depthSort) {
  60981. this._indices = null;
  60982. }
  60983. this._positions = null;
  60984. this._normals = null;
  60985. this._uvs = null;
  60986. this._colors = null;
  60987. if (!this._updatable) {
  60988. this.particles.length = 0;
  60989. }
  60990. return mesh;
  60991. };
  60992. /**
  60993. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  60994. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  60995. * Thus the particles generated from `digest()` have their property `position` set yet.
  60996. * @param mesh ( Mesh ) is the mesh to be digested
  60997. * @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
  60998. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  60999. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  61000. * @returns the current SPS
  61001. */
  61002. SolidParticleSystem.prototype.digest = function (mesh, options) {
  61003. var size = (options && options.facetNb) || 1;
  61004. var number = (options && options.number) || 0;
  61005. var delta = (options && options.delta) || 0;
  61006. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61007. var meshInd = mesh.getIndices();
  61008. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61009. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61010. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61011. var f = 0; // facet counter
  61012. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  61013. // compute size from number
  61014. if (number) {
  61015. number = (number > totalFacets) ? totalFacets : number;
  61016. size = Math.round(totalFacets / number);
  61017. delta = 0;
  61018. }
  61019. else {
  61020. size = (size > totalFacets) ? totalFacets : size;
  61021. }
  61022. var facetPos = []; // submesh positions
  61023. var facetInd = []; // submesh indices
  61024. var facetUV = []; // submesh UV
  61025. var facetCol = []; // submesh colors
  61026. var barycenter = BABYLON.Vector3.Zero();
  61027. var sizeO = size;
  61028. while (f < totalFacets) {
  61029. size = sizeO + Math.floor((1 + delta) * Math.random());
  61030. if (f > totalFacets - size) {
  61031. size = totalFacets - f;
  61032. }
  61033. // reset temp arrays
  61034. facetPos.length = 0;
  61035. facetInd.length = 0;
  61036. facetUV.length = 0;
  61037. facetCol.length = 0;
  61038. // iterate over "size" facets
  61039. var fi = 0;
  61040. for (var j = f * 3; j < (f + size) * 3; j++) {
  61041. facetInd.push(fi);
  61042. var i = meshInd[j];
  61043. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61044. if (meshUV) {
  61045. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61046. }
  61047. if (meshCol) {
  61048. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61049. }
  61050. fi++;
  61051. }
  61052. // create a model shape for each single particle
  61053. var idx = this.nbParticles;
  61054. var shape = this._posToShape(facetPos);
  61055. var shapeUV = this._uvsToShapeUV(facetUV);
  61056. // compute the barycenter of the shape
  61057. var v;
  61058. for (v = 0; v < shape.length; v++) {
  61059. barycenter.addInPlace(shape[v]);
  61060. }
  61061. barycenter.scaleInPlace(1 / shape.length);
  61062. // shift the shape from its barycenter to the origin
  61063. for (v = 0; v < shape.length; v++) {
  61064. shape[v].subtractInPlace(barycenter);
  61065. }
  61066. var bInfo;
  61067. if (this._particlesIntersect) {
  61068. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61069. }
  61070. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61071. // add the particle in the SPS
  61072. var currentPos = this._positions.length;
  61073. var currentInd = this._indices.length;
  61074. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61075. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61076. // initialize the particle position
  61077. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61078. this._index += shape.length;
  61079. idx++;
  61080. this.nbParticles++;
  61081. this._shapeCounter++;
  61082. f += size;
  61083. }
  61084. return this;
  61085. };
  61086. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61087. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61088. var index = 0;
  61089. var idx = 0;
  61090. for (var p = 0; p < this.particles.length; p++) {
  61091. this._particle = this.particles[p];
  61092. this._shape = this._particle._model._shape;
  61093. if (this._particle.rotationQuaternion) {
  61094. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61095. }
  61096. else {
  61097. this._yaw = this._particle.rotation.y;
  61098. this._pitch = this._particle.rotation.x;
  61099. this._roll = this._particle.rotation.z;
  61100. this._quaternionRotationYPR();
  61101. }
  61102. this._quaternionToRotationMatrix();
  61103. this._rotMatrix.invertToRef(this._invertMatrix);
  61104. for (var pt = 0; pt < this._shape.length; pt++) {
  61105. idx = index + pt * 3;
  61106. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  61107. this._fixedNormal32[idx] = this._normal.x;
  61108. this._fixedNormal32[idx + 1] = this._normal.y;
  61109. this._fixedNormal32[idx + 2] = this._normal.z;
  61110. }
  61111. index = idx + 3;
  61112. }
  61113. };
  61114. //reset copy
  61115. SolidParticleSystem.prototype._resetCopy = function () {
  61116. this._copy.position.x = 0;
  61117. this._copy.position.y = 0;
  61118. this._copy.position.z = 0;
  61119. this._copy.rotation.x = 0;
  61120. this._copy.rotation.y = 0;
  61121. this._copy.rotation.z = 0;
  61122. this._copy.rotationQuaternion = null;
  61123. this._copy.scaling.x = 1.0;
  61124. this._copy.scaling.y = 1.0;
  61125. this._copy.scaling.z = 1.0;
  61126. this._copy.uvs.x = 0;
  61127. this._copy.uvs.y = 0;
  61128. this._copy.uvs.z = 1.0;
  61129. this._copy.uvs.w = 1.0;
  61130. this._copy.color = null;
  61131. this._copy.translateFromPivot = false;
  61132. };
  61133. // _meshBuilder : inserts the shape model in the global SPS mesh
  61134. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  61135. var i;
  61136. var u = 0;
  61137. var c = 0;
  61138. var n = 0;
  61139. this._resetCopy();
  61140. if (options && options.positionFunction) { // call to custom positionFunction
  61141. options.positionFunction(this._copy, idx, idxInShape);
  61142. this._mustUnrotateFixedNormals = true;
  61143. }
  61144. if (this._copy.rotationQuaternion) {
  61145. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61146. }
  61147. else {
  61148. this._yaw = this._copy.rotation.y;
  61149. this._pitch = this._copy.rotation.x;
  61150. this._roll = this._copy.rotation.z;
  61151. this._quaternionRotationYPR();
  61152. }
  61153. this._quaternionToRotationMatrix();
  61154. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  61155. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  61156. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  61157. if (this._copy.translateFromPivot) {
  61158. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61159. }
  61160. else {
  61161. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61162. }
  61163. for (i = 0; i < shape.length; i++) {
  61164. this._vertex.x = shape[i].x;
  61165. this._vertex.y = shape[i].y;
  61166. this._vertex.z = shape[i].z;
  61167. if (options && options.vertexFunction) {
  61168. options.vertexFunction(this._copy, this._vertex, i);
  61169. }
  61170. this._vertex.x *= this._copy.scaling.x;
  61171. this._vertex.y *= this._copy.scaling.y;
  61172. this._vertex.z *= this._copy.scaling.z;
  61173. this._vertex.x -= this._scaledPivot.x;
  61174. this._vertex.y -= this._scaledPivot.y;
  61175. this._vertex.z -= this._scaledPivot.z;
  61176. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61177. this._rotated.addInPlace(this._pivotBackTranslation);
  61178. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  61179. if (meshUV) {
  61180. 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);
  61181. u += 2;
  61182. }
  61183. if (this._copy.color) {
  61184. this._color = this._copy.color;
  61185. }
  61186. else if (meshCol && meshCol[c] !== undefined) {
  61187. this._color.r = meshCol[c];
  61188. this._color.g = meshCol[c + 1];
  61189. this._color.b = meshCol[c + 2];
  61190. this._color.a = meshCol[c + 3];
  61191. }
  61192. else {
  61193. this._color.r = 1.0;
  61194. this._color.g = 1.0;
  61195. this._color.b = 1.0;
  61196. this._color.a = 1.0;
  61197. }
  61198. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  61199. c += 4;
  61200. if (!this.recomputeNormals && meshNor) {
  61201. this._normal.x = meshNor[n];
  61202. this._normal.y = meshNor[n + 1];
  61203. this._normal.z = meshNor[n + 2];
  61204. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  61205. normals.push(this._normal.x, this._normal.y, this._normal.z);
  61206. n += 3;
  61207. }
  61208. }
  61209. for (i = 0; i < meshInd.length; i++) {
  61210. var current_ind = p + meshInd[i];
  61211. indices.push(current_ind);
  61212. if (current_ind > 65535) {
  61213. this._needs32Bits = true;
  61214. }
  61215. }
  61216. if (this._pickable) {
  61217. var nbfaces = meshInd.length / 3;
  61218. for (i = 0; i < nbfaces; i++) {
  61219. this.pickedParticles.push({ idx: idx, faceId: i });
  61220. }
  61221. }
  61222. if (this._depthSort) {
  61223. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  61224. }
  61225. return this._copy;
  61226. };
  61227. // returns a shape array from positions array
  61228. SolidParticleSystem.prototype._posToShape = function (positions) {
  61229. var shape = [];
  61230. for (var i = 0; i < positions.length; i += 3) {
  61231. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  61232. }
  61233. return shape;
  61234. };
  61235. // returns a shapeUV array from a Vector4 uvs
  61236. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  61237. var shapeUV = [];
  61238. if (uvs) {
  61239. for (var i = 0; i < uvs.length; i++)
  61240. shapeUV.push(uvs[i]);
  61241. }
  61242. return shapeUV;
  61243. };
  61244. // adds a new particle object in the particles array
  61245. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  61246. if (bInfo === void 0) { bInfo = null; }
  61247. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  61248. this.particles.push(sp);
  61249. return sp;
  61250. };
  61251. /**
  61252. * Adds some particles to the SPS from the model shape. Returns the shape id.
  61253. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  61254. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  61255. * @param nb (positive integer) the number of particles to be created from this model
  61256. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  61257. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  61258. * @returns the number of shapes in the system
  61259. */
  61260. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  61261. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61262. var meshInd = mesh.getIndices();
  61263. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61264. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61265. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61266. var bbInfo;
  61267. if (this._particlesIntersect) {
  61268. bbInfo = mesh.getBoundingInfo();
  61269. }
  61270. var shape = this._posToShape(meshPos);
  61271. var shapeUV = this._uvsToShapeUV(meshUV);
  61272. var posfunc = options ? options.positionFunction : null;
  61273. var vtxfunc = options ? options.vertexFunction : null;
  61274. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  61275. // particles
  61276. var sp;
  61277. var currentCopy;
  61278. var idx = this.nbParticles;
  61279. for (var i = 0; i < nb; i++) {
  61280. var currentPos = this._positions.length;
  61281. var currentInd = this._indices.length;
  61282. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  61283. if (this._updatable) {
  61284. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  61285. sp.position.copyFrom(currentCopy.position);
  61286. sp.rotation.copyFrom(currentCopy.rotation);
  61287. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  61288. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  61289. }
  61290. if (currentCopy.color && sp.color) {
  61291. sp.color.copyFrom(currentCopy.color);
  61292. }
  61293. sp.scaling.copyFrom(currentCopy.scaling);
  61294. sp.uvs.copyFrom(currentCopy.uvs);
  61295. }
  61296. this._index += shape.length;
  61297. idx++;
  61298. }
  61299. this.nbParticles += nb;
  61300. this._shapeCounter++;
  61301. return this._shapeCounter - 1;
  61302. };
  61303. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  61304. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  61305. this._resetCopy();
  61306. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  61307. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  61308. }
  61309. if (this._copy.rotationQuaternion) {
  61310. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61311. }
  61312. else {
  61313. this._yaw = this._copy.rotation.y;
  61314. this._pitch = this._copy.rotation.x;
  61315. this._roll = this._copy.rotation.z;
  61316. this._quaternionRotationYPR();
  61317. }
  61318. this._quaternionToRotationMatrix();
  61319. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61320. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61321. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61322. if (this._copy.translateFromPivot) {
  61323. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61324. }
  61325. else {
  61326. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61327. }
  61328. this._shape = particle._model._shape;
  61329. for (var pt = 0; pt < this._shape.length; pt++) {
  61330. this._vertex.x = this._shape[pt].x;
  61331. this._vertex.y = this._shape[pt].y;
  61332. this._vertex.z = this._shape[pt].z;
  61333. if (particle._model._vertexFunction) {
  61334. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  61335. }
  61336. this._vertex.x *= this._copy.scaling.x;
  61337. this._vertex.y *= this._copy.scaling.y;
  61338. this._vertex.z *= this._copy.scaling.z;
  61339. this._vertex.x -= this._scaledPivot.x;
  61340. this._vertex.y -= this._scaledPivot.y;
  61341. this._vertex.z -= this._scaledPivot.z;
  61342. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61343. this._rotated.addInPlace(this._pivotBackTranslation);
  61344. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  61345. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  61346. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  61347. }
  61348. particle.position.x = 0.0;
  61349. particle.position.y = 0.0;
  61350. particle.position.z = 0.0;
  61351. particle.rotation.x = 0.0;
  61352. particle.rotation.y = 0.0;
  61353. particle.rotation.z = 0.0;
  61354. particle.rotationQuaternion = null;
  61355. particle.scaling.x = 1.0;
  61356. particle.scaling.y = 1.0;
  61357. particle.scaling.z = 1.0;
  61358. particle.uvs.x = 0.0;
  61359. particle.uvs.y = 0.0;
  61360. particle.uvs.z = 1.0;
  61361. particle.uvs.w = 1.0;
  61362. particle.pivot.x = 0.0;
  61363. particle.pivot.y = 0.0;
  61364. particle.pivot.z = 0.0;
  61365. particle.translateFromPivot = false;
  61366. particle.parentId = null;
  61367. };
  61368. /**
  61369. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  61370. * @returns the SPS.
  61371. */
  61372. SolidParticleSystem.prototype.rebuildMesh = function () {
  61373. for (var p = 0; p < this.particles.length; p++) {
  61374. this._rebuildParticle(this.particles[p]);
  61375. }
  61376. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61377. return this;
  61378. };
  61379. /**
  61380. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  61381. * This method calls `updateParticle()` for each particle of the SPS.
  61382. * For an animated SPS, it is usually called within the render loop.
  61383. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  61384. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  61385. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  61386. * @returns the SPS.
  61387. */
  61388. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  61389. if (start === void 0) { start = 0; }
  61390. if (end === void 0) { end = this.nbParticles - 1; }
  61391. if (update === void 0) { update = true; }
  61392. if (!this._updatable) {
  61393. return this;
  61394. }
  61395. // custom beforeUpdate
  61396. this.beforeUpdateParticles(start, end, update);
  61397. this._cam_axisX.x = 1.0;
  61398. this._cam_axisX.y = 0.0;
  61399. this._cam_axisX.z = 0.0;
  61400. this._cam_axisY.x = 0.0;
  61401. this._cam_axisY.y = 1.0;
  61402. this._cam_axisY.z = 0.0;
  61403. this._cam_axisZ.x = 0.0;
  61404. this._cam_axisZ.y = 0.0;
  61405. this._cam_axisZ.z = 1.0;
  61406. // cases when the World Matrix is to be computed first
  61407. if (this.billboard || this._depthSort) {
  61408. this.mesh.computeWorldMatrix(true);
  61409. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  61410. }
  61411. // if the particles will always face the camera
  61412. if (this.billboard) {
  61413. // compute the camera position and un-rotate it by the current mesh rotation
  61414. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  61415. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  61416. this._cam_axisZ.normalize();
  61417. // same for camera up vector extracted from the cam view matrix
  61418. var view = this._camera.getViewMatrix(true);
  61419. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  61420. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  61421. this._cam_axisY.normalize();
  61422. this._cam_axisX.normalize();
  61423. }
  61424. // if depthSort, compute the camera global position in the mesh local system
  61425. if (this._depthSort) {
  61426. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  61427. }
  61428. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61429. var idx = 0; // current position index in the global array positions32
  61430. var index = 0; // position start index in the global array positions32 of the current particle
  61431. var colidx = 0; // current color index in the global array colors32
  61432. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61433. var uvidx = 0; // current uv index in the global array uvs32
  61434. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61435. var pt = 0; // current index in the particle model shape
  61436. if (this.mesh.isFacetDataEnabled) {
  61437. this._computeBoundingBox = true;
  61438. }
  61439. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61440. if (this._computeBoundingBox) {
  61441. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61442. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61443. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61444. }
  61445. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61446. if (this.mesh._boundingInfo) {
  61447. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61448. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61449. }
  61450. }
  61451. }
  61452. // particle loop
  61453. index = this.particles[start]._pos;
  61454. var vpos = (index / 3) | 0;
  61455. colorIndex = vpos * 4;
  61456. uvIndex = vpos * 2;
  61457. for (var p = start; p <= end; p++) {
  61458. this._particle = this.particles[p];
  61459. this._shape = this._particle._model._shape;
  61460. this._shapeUV = this._particle._model._shapeUV;
  61461. // call to custom user function to update the particle properties
  61462. this.updateParticle(this._particle);
  61463. // camera-particle distance for depth sorting
  61464. if (this._depthSort && this._depthSortParticles) {
  61465. var dsp = this.depthSortedParticles[p];
  61466. dsp.ind = this._particle._ind;
  61467. dsp.indicesLength = this._particle._model._indicesLength;
  61468. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61469. }
  61470. // skip the computations for inactive or already invisible particles
  61471. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61472. // increment indexes for the next particle
  61473. pt = this._shape.length;
  61474. index += pt * 3;
  61475. colorIndex += pt * 4;
  61476. uvIndex += pt * 2;
  61477. continue;
  61478. }
  61479. if (this._particle.isVisible) {
  61480. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61481. this._particleHasParent = (this._particle.parentId !== null);
  61482. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61483. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61484. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61485. // particle rotation matrix
  61486. if (this.billboard) {
  61487. this._particle.rotation.x = 0.0;
  61488. this._particle.rotation.y = 0.0;
  61489. }
  61490. if (this._computeParticleRotation || this.billboard) {
  61491. if (this._particle.rotationQuaternion) {
  61492. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61493. }
  61494. else {
  61495. this._yaw = this._particle.rotation.y;
  61496. this._pitch = this._particle.rotation.x;
  61497. this._roll = this._particle.rotation.z;
  61498. this._quaternionRotationYPR();
  61499. }
  61500. this._quaternionToRotationMatrix();
  61501. }
  61502. if (this._particleHasParent) {
  61503. this._parent = this.particles[this._particle.parentId];
  61504. 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];
  61505. 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];
  61506. 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];
  61507. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61508. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61509. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61510. if (this._computeParticleRotation || this.billboard) {
  61511. 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];
  61512. 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];
  61513. 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];
  61514. 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];
  61515. 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];
  61516. 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];
  61517. 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];
  61518. 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];
  61519. 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];
  61520. }
  61521. }
  61522. else {
  61523. this._particle._globalPosition.x = this._particle.position.x;
  61524. this._particle._globalPosition.y = this._particle.position.y;
  61525. this._particle._globalPosition.z = this._particle.position.z;
  61526. if (this._computeParticleRotation || this.billboard) {
  61527. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61528. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61529. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61530. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61531. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61532. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61533. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61534. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61535. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61536. }
  61537. }
  61538. if (this._particle.translateFromPivot) {
  61539. this._pivotBackTranslation.x = 0.0;
  61540. this._pivotBackTranslation.y = 0.0;
  61541. this._pivotBackTranslation.z = 0.0;
  61542. }
  61543. else {
  61544. this._pivotBackTranslation.x = this._scaledPivot.x;
  61545. this._pivotBackTranslation.y = this._scaledPivot.y;
  61546. this._pivotBackTranslation.z = this._scaledPivot.z;
  61547. }
  61548. // particle vertex loop
  61549. for (pt = 0; pt < this._shape.length; pt++) {
  61550. idx = index + pt * 3;
  61551. colidx = colorIndex + pt * 4;
  61552. uvidx = uvIndex + pt * 2;
  61553. this._vertex.x = this._shape[pt].x;
  61554. this._vertex.y = this._shape[pt].y;
  61555. this._vertex.z = this._shape[pt].z;
  61556. if (this._computeParticleVertex) {
  61557. this.updateParticleVertex(this._particle, this._vertex, pt);
  61558. }
  61559. // positions
  61560. this._vertex.x *= this._particle.scaling.x;
  61561. this._vertex.y *= this._particle.scaling.y;
  61562. this._vertex.z *= this._particle.scaling.z;
  61563. this._vertex.x -= this._scaledPivot.x;
  61564. this._vertex.y -= this._scaledPivot.y;
  61565. this._vertex.z -= this._scaledPivot.z;
  61566. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61567. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61568. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61569. this._rotated.x += this._pivotBackTranslation.x;
  61570. this._rotated.y += this._pivotBackTranslation.y;
  61571. this._rotated.z += this._pivotBackTranslation.z;
  61572. 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;
  61573. 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;
  61574. 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;
  61575. if (this._computeBoundingBox) {
  61576. if (this._positions32[idx] < this._minimum.x) {
  61577. this._minimum.x = this._positions32[idx];
  61578. }
  61579. if (this._positions32[idx] > this._maximum.x) {
  61580. this._maximum.x = this._positions32[idx];
  61581. }
  61582. if (this._positions32[idx + 1] < this._minimum.y) {
  61583. this._minimum.y = this._positions32[idx + 1];
  61584. }
  61585. if (this._positions32[idx + 1] > this._maximum.y) {
  61586. this._maximum.y = this._positions32[idx + 1];
  61587. }
  61588. if (this._positions32[idx + 2] < this._minimum.z) {
  61589. this._minimum.z = this._positions32[idx + 2];
  61590. }
  61591. if (this._positions32[idx + 2] > this._maximum.z) {
  61592. this._maximum.z = this._positions32[idx + 2];
  61593. }
  61594. }
  61595. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  61596. if (!this._computeParticleVertex) {
  61597. this._normal.x = this._fixedNormal32[idx];
  61598. this._normal.y = this._fixedNormal32[idx + 1];
  61599. this._normal.z = this._fixedNormal32[idx + 2];
  61600. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  61601. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  61602. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  61603. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61604. 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;
  61605. 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;
  61606. }
  61607. if (this._computeParticleColor && this._particle.color) {
  61608. this._colors32[colidx] = this._particle.color.r;
  61609. this._colors32[colidx + 1] = this._particle.color.g;
  61610. this._colors32[colidx + 2] = this._particle.color.b;
  61611. this._colors32[colidx + 3] = this._particle.color.a;
  61612. }
  61613. if (this._computeParticleTexture) {
  61614. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61615. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61616. }
  61617. }
  61618. }
  61619. // particle just set invisible : scaled to zero and positioned at the origin
  61620. else {
  61621. this._particle._stillInvisible = true; // mark the particle as invisible
  61622. for (pt = 0; pt < this._shape.length; pt++) {
  61623. idx = index + pt * 3;
  61624. colidx = colorIndex + pt * 4;
  61625. uvidx = uvIndex + pt * 2;
  61626. this._positions32[idx] = 0.0;
  61627. this._positions32[idx + 1] = 0.0;
  61628. this._positions32[idx + 2] = 0.0;
  61629. this._normals32[idx] = 0.0;
  61630. this._normals32[idx + 1] = 0.0;
  61631. this._normals32[idx + 2] = 0.0;
  61632. if (this._computeParticleColor && this._particle.color) {
  61633. this._colors32[colidx] = this._particle.color.r;
  61634. this._colors32[colidx + 1] = this._particle.color.g;
  61635. this._colors32[colidx + 2] = this._particle.color.b;
  61636. this._colors32[colidx + 3] = this._particle.color.a;
  61637. }
  61638. if (this._computeParticleTexture) {
  61639. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61640. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61641. }
  61642. }
  61643. }
  61644. // if the particle intersections must be computed : update the bbInfo
  61645. if (this._particlesIntersect) {
  61646. var bInfo = this._particle._boundingInfo;
  61647. var bBox = bInfo.boundingBox;
  61648. var bSphere = bInfo.boundingSphere;
  61649. if (!this._bSphereOnly) {
  61650. // place, scale and rotate the particle bbox within the SPS local system, then update it
  61651. for (var b = 0; b < bBox.vectors.length; b++) {
  61652. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  61653. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  61654. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  61655. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61656. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61657. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61658. 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;
  61659. 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;
  61660. 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;
  61661. }
  61662. bBox._update(this.mesh._worldMatrix);
  61663. }
  61664. // place and scale the particle bouding sphere in the SPS local system, then update it
  61665. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  61666. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  61667. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  61668. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  61669. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  61670. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  61671. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  61672. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  61673. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  61674. 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));
  61675. bSphere._update(this.mesh._worldMatrix);
  61676. }
  61677. // increment indexes for the next particle
  61678. index = idx + 3;
  61679. colorIndex = colidx + 4;
  61680. uvIndex = uvidx + 2;
  61681. }
  61682. // if the VBO must be updated
  61683. if (update) {
  61684. if (this._computeParticleColor) {
  61685. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  61686. }
  61687. if (this._computeParticleTexture) {
  61688. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  61689. }
  61690. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61691. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  61692. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  61693. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  61694. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  61695. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  61696. for (var i = 0; i < this._normals32.length; i++) {
  61697. this._fixedNormal32[i] = this._normals32[i];
  61698. }
  61699. }
  61700. if (!this.mesh.areNormalsFrozen) {
  61701. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  61702. }
  61703. }
  61704. if (this._depthSort && this._depthSortParticles) {
  61705. this.depthSortedParticles.sort(this._depthSortFunction);
  61706. var dspl = this.depthSortedParticles.length;
  61707. var sorted = 0;
  61708. var lind = 0;
  61709. var sind = 0;
  61710. var sid = 0;
  61711. for (sorted = 0; sorted < dspl; sorted++) {
  61712. lind = this.depthSortedParticles[sorted].indicesLength;
  61713. sind = this.depthSortedParticles[sorted].ind;
  61714. for (var i = 0; i < lind; i++) {
  61715. this._indices32[sid] = this._indices[sind + i];
  61716. sid++;
  61717. }
  61718. }
  61719. this.mesh.updateIndices(this._indices32);
  61720. }
  61721. }
  61722. if (this._computeBoundingBox) {
  61723. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  61724. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  61725. }
  61726. this.afterUpdateParticles(start, end, update);
  61727. return this;
  61728. };
  61729. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  61730. this._halfroll = this._roll * 0.5;
  61731. this._halfpitch = this._pitch * 0.5;
  61732. this._halfyaw = this._yaw * 0.5;
  61733. this._sinRoll = Math.sin(this._halfroll);
  61734. this._cosRoll = Math.cos(this._halfroll);
  61735. this._sinPitch = Math.sin(this._halfpitch);
  61736. this._cosPitch = Math.cos(this._halfpitch);
  61737. this._sinYaw = Math.sin(this._halfyaw);
  61738. this._cosYaw = Math.cos(this._halfyaw);
  61739. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  61740. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  61741. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  61742. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  61743. };
  61744. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  61745. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  61746. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  61747. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  61748. this._rotMatrix.m[3] = 0;
  61749. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  61750. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  61751. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  61752. this._rotMatrix.m[7] = 0;
  61753. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  61754. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  61755. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  61756. this._rotMatrix.m[11] = 0;
  61757. this._rotMatrix.m[12] = 0;
  61758. this._rotMatrix.m[13] = 0;
  61759. this._rotMatrix.m[14] = 0;
  61760. this._rotMatrix.m[15] = 1.0;
  61761. };
  61762. /**
  61763. * Disposes the SPS.
  61764. */
  61765. SolidParticleSystem.prototype.dispose = function () {
  61766. this.mesh.dispose();
  61767. this.vars = null;
  61768. // drop references to internal big arrays for the GC
  61769. this._positions = null;
  61770. this._indices = null;
  61771. this._normals = null;
  61772. this._uvs = null;
  61773. this._colors = null;
  61774. this._indices32 = null;
  61775. this._positions32 = null;
  61776. this._normals32 = null;
  61777. this._fixedNormal32 = null;
  61778. this._uvs32 = null;
  61779. this._colors32 = null;
  61780. this.pickedParticles = null;
  61781. };
  61782. /**
  61783. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  61784. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61785. * @returns the SPS.
  61786. */
  61787. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  61788. if (!this._isVisibilityBoxLocked) {
  61789. this.mesh.refreshBoundingInfo();
  61790. }
  61791. return this;
  61792. };
  61793. /**
  61794. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  61795. * @param size the size (float) of the visibility box
  61796. * note : this doesn't lock the SPS mesh bounding box.
  61797. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61798. */
  61799. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  61800. var vis = size / 2;
  61801. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  61802. };
  61803. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  61804. /**
  61805. * Gets whether the SPS as always visible or not
  61806. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61807. */
  61808. get: function () {
  61809. return this._alwaysVisible;
  61810. },
  61811. /**
  61812. * Sets the SPS as always visible or not
  61813. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61814. */
  61815. set: function (val) {
  61816. this._alwaysVisible = val;
  61817. this.mesh.alwaysSelectAsActiveMesh = val;
  61818. },
  61819. enumerable: true,
  61820. configurable: true
  61821. });
  61822. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  61823. /**
  61824. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61825. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61826. */
  61827. get: function () {
  61828. return this._isVisibilityBoxLocked;
  61829. },
  61830. /**
  61831. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61832. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61833. */
  61834. set: function (val) {
  61835. this._isVisibilityBoxLocked = val;
  61836. var boundingInfo = this.mesh.getBoundingInfo();
  61837. boundingInfo.isLocked = val;
  61838. },
  61839. enumerable: true,
  61840. configurable: true
  61841. });
  61842. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  61843. /**
  61844. * Gets if `setParticles()` computes the particle rotations or not.
  61845. * Default value : true. The SPS is faster when it's set to false.
  61846. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61847. */
  61848. get: function () {
  61849. return this._computeParticleRotation;
  61850. },
  61851. /**
  61852. * Tells to `setParticles()` to compute the particle rotations or not.
  61853. * Default value : true. The SPS is faster when it's set to false.
  61854. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61855. */
  61856. set: function (val) {
  61857. this._computeParticleRotation = val;
  61858. },
  61859. enumerable: true,
  61860. configurable: true
  61861. });
  61862. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  61863. /**
  61864. * Gets if `setParticles()` computes the particle colors or not.
  61865. * Default value : true. The SPS is faster when it's set to false.
  61866. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61867. */
  61868. get: function () {
  61869. return this._computeParticleColor;
  61870. },
  61871. /**
  61872. * Tells to `setParticles()` to compute the particle colors or not.
  61873. * Default value : true. The SPS is faster when it's set to false.
  61874. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61875. */
  61876. set: function (val) {
  61877. this._computeParticleColor = val;
  61878. },
  61879. enumerable: true,
  61880. configurable: true
  61881. });
  61882. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  61883. /**
  61884. * Gets if `setParticles()` computes the particle textures or not.
  61885. * Default value : true. The SPS is faster when it's set to false.
  61886. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  61887. */
  61888. get: function () {
  61889. return this._computeParticleTexture;
  61890. },
  61891. set: function (val) {
  61892. this._computeParticleTexture = val;
  61893. },
  61894. enumerable: true,
  61895. configurable: true
  61896. });
  61897. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  61898. /**
  61899. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  61900. * Default value : false. The SPS is faster when it's set to false.
  61901. * Note : the particle custom vertex positions aren't stored values.
  61902. */
  61903. get: function () {
  61904. return this._computeParticleVertex;
  61905. },
  61906. /**
  61907. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  61908. * Default value : false. The SPS is faster when it's set to false.
  61909. * Note : the particle custom vertex positions aren't stored values.
  61910. */
  61911. set: function (val) {
  61912. this._computeParticleVertex = val;
  61913. },
  61914. enumerable: true,
  61915. configurable: true
  61916. });
  61917. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  61918. /**
  61919. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  61920. */
  61921. get: function () {
  61922. return this._computeBoundingBox;
  61923. },
  61924. /**
  61925. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  61926. */
  61927. set: function (val) {
  61928. this._computeBoundingBox = val;
  61929. },
  61930. enumerable: true,
  61931. configurable: true
  61932. });
  61933. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  61934. /**
  61935. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  61936. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61937. * Default : `true`
  61938. */
  61939. get: function () {
  61940. return this._depthSortParticles;
  61941. },
  61942. /**
  61943. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  61944. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61945. * Default : `true`
  61946. */
  61947. set: function (val) {
  61948. this._depthSortParticles = val;
  61949. },
  61950. enumerable: true,
  61951. configurable: true
  61952. });
  61953. // =======================================================================
  61954. // Particle behavior logic
  61955. // these following methods may be overwritten by the user to fit his needs
  61956. /**
  61957. * This function does nothing. It may be overwritten to set all the particle first values.
  61958. * The SPS doesn't call this function, you may have to call it by your own.
  61959. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61960. */
  61961. SolidParticleSystem.prototype.initParticles = function () {
  61962. };
  61963. /**
  61964. * This function does nothing. It may be overwritten to recycle a particle.
  61965. * The SPS doesn't call this function, you may have to call it by your own.
  61966. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61967. * @param particle The particle to recycle
  61968. * @returns the recycled particle
  61969. */
  61970. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  61971. return particle;
  61972. };
  61973. /**
  61974. * Updates a particle : this function should be overwritten by the user.
  61975. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  61976. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61977. * @example : just set a particle position or velocity and recycle conditions
  61978. * @param particle The particle to update
  61979. * @returns the updated particle
  61980. */
  61981. SolidParticleSystem.prototype.updateParticle = function (particle) {
  61982. return particle;
  61983. };
  61984. /**
  61985. * Updates a vertex of a particle : it can be overwritten by the user.
  61986. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  61987. * @param particle the current particle
  61988. * @param vertex the current index of the current particle
  61989. * @param pt the index of the current vertex in the particle shape
  61990. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  61991. * @example : just set a vertex particle position
  61992. * @returns the updated vertex
  61993. */
  61994. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  61995. return vertex;
  61996. };
  61997. /**
  61998. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  61999. * This does nothing and may be overwritten by the user.
  62000. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62001. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62002. * @param update the boolean update value actually passed to setParticles()
  62003. */
  62004. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  62005. };
  62006. /**
  62007. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  62008. * This will be passed three parameters.
  62009. * This does nothing and may be overwritten by the user.
  62010. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62011. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62012. * @param update the boolean update value actually passed to setParticles()
  62013. */
  62014. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  62015. };
  62016. return SolidParticleSystem;
  62017. }());
  62018. BABYLON.SolidParticleSystem = SolidParticleSystem;
  62019. })(BABYLON || (BABYLON = {}));
  62020. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  62021. var BABYLON;
  62022. (function (BABYLON) {
  62023. /**
  62024. * Class containing static functions to help procedurally build meshes
  62025. */
  62026. var MeshBuilder = /** @class */ (function () {
  62027. function MeshBuilder() {
  62028. }
  62029. MeshBuilder.updateSideOrientation = function (orientation) {
  62030. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62031. return BABYLON.Mesh.DOUBLESIDE;
  62032. }
  62033. if (orientation === undefined || orientation === null) {
  62034. return BABYLON.Mesh.FRONTSIDE;
  62035. }
  62036. return orientation;
  62037. };
  62038. /**
  62039. * Creates a box mesh
  62040. * * The parameter `size` sets the size (float) of each box side (default 1)
  62041. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62042. * * 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)
  62043. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62044. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62045. * * 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
  62046. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62047. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62048. * @param name defines the name of the mesh
  62049. * @param options defines the options used to create the mesh
  62050. * @param scene defines the hosting scene
  62051. * @returns the box mesh
  62052. */
  62053. MeshBuilder.CreateBox = function (name, options, scene) {
  62054. if (scene === void 0) { scene = null; }
  62055. var box = new BABYLON.Mesh(name, scene);
  62056. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62057. box._originalBuilderSideOrientation = options.sideOrientation;
  62058. var vertexData = BABYLON.VertexData.CreateBox(options);
  62059. vertexData.applyToMesh(box, options.updatable);
  62060. return box;
  62061. };
  62062. /**
  62063. * Creates a sphere mesh
  62064. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62065. * * 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`)
  62066. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62067. * * 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
  62068. * * 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)
  62069. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62070. * * 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
  62071. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62072. * @param name defines the name of the mesh
  62073. * @param options defines the options used to create the mesh
  62074. * @param scene defines the hosting scene
  62075. * @returns the sphere mesh
  62076. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62077. */
  62078. MeshBuilder.CreateSphere = function (name, options, scene) {
  62079. var sphere = new BABYLON.Mesh(name, scene);
  62080. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62081. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62082. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62083. vertexData.applyToMesh(sphere, options.updatable);
  62084. return sphere;
  62085. };
  62086. /**
  62087. * Creates a plane polygonal mesh. By default, this is a disc
  62088. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62089. * * 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
  62090. * * 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
  62091. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62092. * * 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
  62093. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62094. * @param name defines the name of the mesh
  62095. * @param options defines the options used to create the mesh
  62096. * @param scene defines the hosting scene
  62097. * @returns the plane polygonal mesh
  62098. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62099. */
  62100. MeshBuilder.CreateDisc = function (name, options, scene) {
  62101. if (scene === void 0) { scene = null; }
  62102. var disc = new BABYLON.Mesh(name, scene);
  62103. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62104. disc._originalBuilderSideOrientation = options.sideOrientation;
  62105. var vertexData = BABYLON.VertexData.CreateDisc(options);
  62106. vertexData.applyToMesh(disc, options.updatable);
  62107. return disc;
  62108. };
  62109. /**
  62110. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  62111. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  62112. * * 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`)
  62113. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  62114. * * 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
  62115. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62116. * * 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
  62117. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62118. * @param name defines the name of the mesh
  62119. * @param options defines the options used to create the mesh
  62120. * @param scene defines the hosting scene
  62121. * @returns the icosahedron mesh
  62122. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  62123. */
  62124. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  62125. var sphere = new BABYLON.Mesh(name, scene);
  62126. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62127. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62128. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  62129. vertexData.applyToMesh(sphere, options.updatable);
  62130. return sphere;
  62131. };
  62132. ;
  62133. /**
  62134. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62135. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  62136. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  62137. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  62138. * * 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
  62139. * * 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
  62140. * * 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
  62141. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62142. * * 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
  62143. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62144. * * 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
  62145. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  62146. * * 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
  62147. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  62148. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62149. * @param name defines the name of the mesh
  62150. * @param options defines the options used to create the mesh
  62151. * @param scene defines the hosting scene
  62152. * @returns the ribbon mesh
  62153. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  62154. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62155. */
  62156. MeshBuilder.CreateRibbon = function (name, options, scene) {
  62157. if (scene === void 0) { scene = null; }
  62158. var pathArray = options.pathArray;
  62159. var closeArray = options.closeArray;
  62160. var closePath = options.closePath;
  62161. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62162. var instance = options.instance;
  62163. var updatable = options.updatable;
  62164. if (instance) { // existing ribbon instance update
  62165. // positionFunction : ribbon case
  62166. // only pathArray and sideOrientation parameters are taken into account for positions update
  62167. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  62168. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  62169. var positionFunction = function (positions) {
  62170. var minlg = pathArray[0].length;
  62171. var i = 0;
  62172. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  62173. for (var si = 1; si <= ns; si++) {
  62174. for (var p = 0; p < pathArray.length; p++) {
  62175. var path = pathArray[p];
  62176. var l = path.length;
  62177. minlg = (minlg < l) ? minlg : l;
  62178. var j = 0;
  62179. while (j < minlg) {
  62180. positions[i] = path[j].x;
  62181. positions[i + 1] = path[j].y;
  62182. positions[i + 2] = path[j].z;
  62183. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  62184. BABYLON.Tmp.Vector3[0].x = path[j].x;
  62185. }
  62186. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  62187. BABYLON.Tmp.Vector3[1].x = path[j].x;
  62188. }
  62189. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  62190. BABYLON.Tmp.Vector3[0].y = path[j].y;
  62191. }
  62192. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  62193. BABYLON.Tmp.Vector3[1].y = path[j].y;
  62194. }
  62195. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  62196. BABYLON.Tmp.Vector3[0].z = path[j].z;
  62197. }
  62198. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  62199. BABYLON.Tmp.Vector3[1].z = path[j].z;
  62200. }
  62201. j++;
  62202. i += 3;
  62203. }
  62204. if (instance._closePath) {
  62205. positions[i] = path[0].x;
  62206. positions[i + 1] = path[0].y;
  62207. positions[i + 2] = path[0].z;
  62208. i += 3;
  62209. }
  62210. }
  62211. }
  62212. };
  62213. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62214. positionFunction(positions);
  62215. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  62216. instance._boundingInfo.update(instance._worldMatrix);
  62217. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62218. if (options.colors) {
  62219. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62220. for (var c = 0; c < options.colors.length; c++) {
  62221. colors[c * 4] = options.colors[c].r;
  62222. colors[c * 4 + 1] = options.colors[c].g;
  62223. colors[c * 4 + 2] = options.colors[c].b;
  62224. colors[c * 4 + 3] = options.colors[c].a;
  62225. }
  62226. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  62227. }
  62228. if (options.uvs) {
  62229. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62230. for (var i = 0; i < options.uvs.length; i++) {
  62231. uvs[i * 2] = options.uvs[i].x;
  62232. uvs[i * 2 + 1] = options.uvs[i].y;
  62233. }
  62234. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  62235. }
  62236. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  62237. var indices = instance.getIndices();
  62238. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62239. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  62240. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  62241. if (instance._closePath) {
  62242. var indexFirst = 0;
  62243. var indexLast = 0;
  62244. for (var p = 0; p < pathArray.length; p++) {
  62245. indexFirst = instance._idx[p] * 3;
  62246. if (p + 1 < pathArray.length) {
  62247. indexLast = (instance._idx[p + 1] - 1) * 3;
  62248. }
  62249. else {
  62250. indexLast = normals.length - 3;
  62251. }
  62252. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  62253. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  62254. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  62255. normals[indexLast] = normals[indexFirst];
  62256. normals[indexLast + 1] = normals[indexFirst + 1];
  62257. normals[indexLast + 2] = normals[indexFirst + 2];
  62258. }
  62259. }
  62260. if (!(instance.areNormalsFrozen)) {
  62261. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  62262. }
  62263. }
  62264. return instance;
  62265. }
  62266. else { // new ribbon creation
  62267. var ribbon = new BABYLON.Mesh(name, scene);
  62268. ribbon._originalBuilderSideOrientation = sideOrientation;
  62269. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  62270. if (closePath) {
  62271. ribbon._idx = vertexData._idx;
  62272. }
  62273. ribbon._closePath = closePath;
  62274. ribbon._closeArray = closeArray;
  62275. vertexData.applyToMesh(ribbon, updatable);
  62276. return ribbon;
  62277. }
  62278. };
  62279. /**
  62280. * Creates a cylinder or a cone mesh
  62281. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  62282. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  62283. * * 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.
  62284. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  62285. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  62286. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  62287. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  62288. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  62289. * * 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).
  62290. * * 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
  62291. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  62292. * * 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
  62293. * * 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.
  62294. * * If `enclose` is false, a ring surface is one element.
  62295. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  62296. * * 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
  62297. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62298. * * 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
  62299. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62300. * @param name defines the name of the mesh
  62301. * @param options defines the options used to create the mesh
  62302. * @param scene defines the hosting scene
  62303. * @returns the cylinder mesh
  62304. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  62305. */
  62306. MeshBuilder.CreateCylinder = function (name, options, scene) {
  62307. var cylinder = new BABYLON.Mesh(name, scene);
  62308. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62309. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  62310. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  62311. vertexData.applyToMesh(cylinder, options.updatable);
  62312. return cylinder;
  62313. };
  62314. /**
  62315. * Creates a torus mesh
  62316. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  62317. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  62318. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  62319. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62320. * * 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
  62321. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62322. * @param name defines the name of the mesh
  62323. * @param options defines the options used to create the mesh
  62324. * @param scene defines the hosting scene
  62325. * @returns the torus mesh
  62326. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  62327. */
  62328. MeshBuilder.CreateTorus = function (name, options, scene) {
  62329. var torus = new BABYLON.Mesh(name, scene);
  62330. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62331. torus._originalBuilderSideOrientation = options.sideOrientation;
  62332. var vertexData = BABYLON.VertexData.CreateTorus(options);
  62333. vertexData.applyToMesh(torus, options.updatable);
  62334. return torus;
  62335. };
  62336. /**
  62337. * Creates a torus knot mesh
  62338. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  62339. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  62340. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  62341. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  62342. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62343. * * 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
  62344. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62345. * @param name defines the name of the mesh
  62346. * @param options defines the options used to create the mesh
  62347. * @param scene defines the hosting scene
  62348. * @returns the torus knot mesh
  62349. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  62350. */
  62351. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  62352. var torusKnot = new BABYLON.Mesh(name, scene);
  62353. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62354. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  62355. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  62356. vertexData.applyToMesh(torusKnot, options.updatable);
  62357. return torusKnot;
  62358. };
  62359. /**
  62360. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  62361. * * 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
  62362. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  62363. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  62364. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  62365. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  62366. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  62367. * * 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
  62368. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  62369. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62370. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  62371. * @param name defines the name of the new line system
  62372. * @param options defines the options used to create the line system
  62373. * @param scene defines the hosting scene
  62374. * @returns a new line system mesh
  62375. */
  62376. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  62377. var instance = options.instance;
  62378. var lines = options.lines;
  62379. var colors = options.colors;
  62380. if (instance) { // lines update
  62381. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62382. var vertexColor;
  62383. var lineColors;
  62384. if (colors) {
  62385. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62386. }
  62387. var i = 0;
  62388. var c = 0;
  62389. for (var l = 0; l < lines.length; l++) {
  62390. var points = lines[l];
  62391. for (var p = 0; p < points.length; p++) {
  62392. positions[i] = points[p].x;
  62393. positions[i + 1] = points[p].y;
  62394. positions[i + 2] = points[p].z;
  62395. if (colors && vertexColor) {
  62396. lineColors = colors[l];
  62397. vertexColor[c] = lineColors[p].r;
  62398. vertexColor[c + 1] = lineColors[p].g;
  62399. vertexColor[c + 2] = lineColors[p].b;
  62400. vertexColor[c + 3] = lineColors[p].a;
  62401. c += 4;
  62402. }
  62403. i += 3;
  62404. }
  62405. }
  62406. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62407. if (colors && vertexColor) {
  62408. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  62409. }
  62410. return instance;
  62411. }
  62412. // line system creation
  62413. var useVertexColor = (colors) ? true : false;
  62414. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  62415. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  62416. vertexData.applyToMesh(lineSystem, options.updatable);
  62417. return lineSystem;
  62418. };
  62419. /**
  62420. * Creates a line mesh
  62421. * 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
  62422. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62423. * * The parameter `points` is an array successive Vector3
  62424. * * 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
  62425. * * The optional parameter `colors` is an array of successive Color4, one per line point
  62426. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  62427. * * When updating an instance, remember that only point positions can change, not the number of points
  62428. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62429. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62430. * @param name defines the name of the new line system
  62431. * @param options defines the options used to create the line system
  62432. * @param scene defines the hosting scene
  62433. * @returns a new line mesh
  62434. */
  62435. MeshBuilder.CreateLines = function (name, options, scene) {
  62436. if (scene === void 0) { scene = null; }
  62437. var colors = (options.colors) ? [options.colors] : null;
  62438. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62439. return lines;
  62440. };
  62441. /**
  62442. * Creates a dashed line mesh
  62443. * * 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
  62444. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62445. * * The parameter `points` is an array successive Vector3
  62446. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62447. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62448. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62449. * * 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
  62450. * * When updating an instance, remember that only point positions can change, not the number of points
  62451. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62452. * @param name defines the name of the mesh
  62453. * @param options defines the options used to create the mesh
  62454. * @param scene defines the hosting scene
  62455. * @returns the dashed line mesh
  62456. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62457. */
  62458. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62459. if (scene === void 0) { scene = null; }
  62460. var points = options.points;
  62461. var instance = options.instance;
  62462. var gapSize = options.gapSize || 1;
  62463. var dashSize = options.dashSize || 3;
  62464. if (instance) { // dashed lines update
  62465. var positionFunction = function (positions) {
  62466. var curvect = BABYLON.Vector3.Zero();
  62467. var nbSeg = positions.length / 6;
  62468. var lg = 0;
  62469. var nb = 0;
  62470. var shft = 0;
  62471. var dashshft = 0;
  62472. var curshft = 0;
  62473. var p = 0;
  62474. var i = 0;
  62475. var j = 0;
  62476. for (i = 0; i < points.length - 1; i++) {
  62477. points[i + 1].subtractToRef(points[i], curvect);
  62478. lg += curvect.length();
  62479. }
  62480. shft = lg / nbSeg;
  62481. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62482. for (i = 0; i < points.length - 1; i++) {
  62483. points[i + 1].subtractToRef(points[i], curvect);
  62484. nb = Math.floor(curvect.length() / shft);
  62485. curvect.normalize();
  62486. j = 0;
  62487. while (j < nb && p < positions.length) {
  62488. curshft = shft * j;
  62489. positions[p] = points[i].x + curshft * curvect.x;
  62490. positions[p + 1] = points[i].y + curshft * curvect.y;
  62491. positions[p + 2] = points[i].z + curshft * curvect.z;
  62492. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62493. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62494. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62495. p += 6;
  62496. j++;
  62497. }
  62498. }
  62499. while (p < positions.length) {
  62500. positions[p] = points[i].x;
  62501. positions[p + 1] = points[i].y;
  62502. positions[p + 2] = points[i].z;
  62503. p += 3;
  62504. }
  62505. };
  62506. instance.updateMeshPositions(positionFunction, false);
  62507. return instance;
  62508. }
  62509. // dashed lines creation
  62510. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62511. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62512. vertexData.applyToMesh(dashedLines, options.updatable);
  62513. dashedLines.dashSize = dashSize;
  62514. dashedLines.gapSize = gapSize;
  62515. return dashedLines;
  62516. };
  62517. /**
  62518. * 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.
  62519. * * 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.
  62520. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62521. * * 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.
  62522. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62523. * * 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
  62524. * * 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
  62525. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62526. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62527. * * 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
  62528. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62529. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62530. * @param name defines the name of the mesh
  62531. * @param options defines the options used to create the mesh
  62532. * @param scene defines the hosting scene
  62533. * @returns the extruded shape mesh
  62534. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62535. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62536. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62537. */
  62538. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62539. if (scene === void 0) { scene = null; }
  62540. var path = options.path;
  62541. var shape = options.shape;
  62542. var scale = options.scale || 1;
  62543. var rotation = options.rotation || 0;
  62544. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62545. var updatable = options.updatable;
  62546. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62547. var instance = options.instance || null;
  62548. var invertUV = options.invertUV || false;
  62549. 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);
  62550. };
  62551. /**
  62552. * Creates an custom extruded shape mesh.
  62553. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62554. * * 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.
  62555. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62556. * * 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
  62557. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62558. * * 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
  62559. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62560. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62561. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62562. * * 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
  62563. * * 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
  62564. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62565. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62566. * * 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
  62567. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62568. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62569. * @param name defines the name of the mesh
  62570. * @param options defines the options used to create the mesh
  62571. * @param scene defines the hosting scene
  62572. * @returns the custom extruded shape mesh
  62573. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  62574. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62575. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62576. */
  62577. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  62578. var path = options.path;
  62579. var shape = options.shape;
  62580. var scaleFunction = options.scaleFunction || (function () { return 1; });
  62581. var rotationFunction = options.rotationFunction || (function () { return 0; });
  62582. var ribbonCloseArray = options.ribbonCloseArray || false;
  62583. var ribbonClosePath = options.ribbonClosePath || false;
  62584. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62585. var updatable = options.updatable;
  62586. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62587. var instance = options.instance;
  62588. var invertUV = options.invertUV || false;
  62589. 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);
  62590. };
  62591. /**
  62592. * Creates lathe mesh.
  62593. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  62594. * * 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
  62595. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  62596. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  62597. * * 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
  62598. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  62599. * * 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
  62600. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62601. * * 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
  62602. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62603. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62604. * @param name defines the name of the mesh
  62605. * @param options defines the options used to create the mesh
  62606. * @param scene defines the hosting scene
  62607. * @returns the lathe mesh
  62608. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  62609. */
  62610. MeshBuilder.CreateLathe = function (name, options, scene) {
  62611. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  62612. var closed = (options.closed === undefined) ? true : options.closed;
  62613. var shape = options.shape;
  62614. var radius = options.radius || 1;
  62615. var tessellation = options.tessellation || 64;
  62616. var updatable = options.updatable;
  62617. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62618. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62619. var pi2 = Math.PI * 2;
  62620. var paths = new Array();
  62621. var invertUV = options.invertUV || false;
  62622. var i = 0;
  62623. var p = 0;
  62624. var step = pi2 / tessellation * arc;
  62625. var rotated;
  62626. var path = new Array();
  62627. for (i = 0; i <= tessellation; i++) {
  62628. var path = [];
  62629. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  62630. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  62631. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  62632. }
  62633. for (p = 0; p < shape.length; p++) {
  62634. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  62635. path.push(rotated);
  62636. }
  62637. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  62638. 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));
  62639. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  62640. }
  62641. paths.push(path);
  62642. }
  62643. // lathe ribbon
  62644. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62645. return lathe;
  62646. };
  62647. /**
  62648. * Creates a plane mesh
  62649. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  62650. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  62651. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  62652. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62653. * * 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
  62654. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62655. * @param name defines the name of the mesh
  62656. * @param options defines the options used to create the mesh
  62657. * @param scene defines the hosting scene
  62658. * @returns the plane mesh
  62659. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62660. */
  62661. MeshBuilder.CreatePlane = function (name, options, scene) {
  62662. var plane = new BABYLON.Mesh(name, scene);
  62663. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62664. plane._originalBuilderSideOrientation = options.sideOrientation;
  62665. var vertexData = BABYLON.VertexData.CreatePlane(options);
  62666. vertexData.applyToMesh(plane, options.updatable);
  62667. if (options.sourcePlane) {
  62668. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  62669. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  62670. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  62671. plane.rotate(vectorProduct, product);
  62672. }
  62673. return plane;
  62674. };
  62675. /**
  62676. * Creates a ground mesh
  62677. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  62678. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  62679. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62680. * @param name defines the name of the mesh
  62681. * @param options defines the options used to create the mesh
  62682. * @param scene defines the hosting scene
  62683. * @returns the ground mesh
  62684. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62685. */
  62686. MeshBuilder.CreateGround = function (name, options, scene) {
  62687. var ground = new BABYLON.GroundMesh(name, scene);
  62688. ground._setReady(false);
  62689. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  62690. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  62691. ground._width = options.width || 1;
  62692. ground._height = options.height || 1;
  62693. ground._maxX = ground._width / 2;
  62694. ground._maxZ = ground._height / 2;
  62695. ground._minX = -ground._maxX;
  62696. ground._minZ = -ground._maxZ;
  62697. var vertexData = BABYLON.VertexData.CreateGround(options);
  62698. vertexData.applyToMesh(ground, options.updatable);
  62699. ground._setReady(true);
  62700. return ground;
  62701. };
  62702. /**
  62703. * Creates a tiled ground mesh
  62704. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  62705. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  62706. * * 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
  62707. * * 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
  62708. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62709. * @param name defines the name of the mesh
  62710. * @param options defines the options used to create the mesh
  62711. * @param scene defines the hosting scene
  62712. * @returns the tiled ground mesh
  62713. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  62714. */
  62715. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  62716. var tiledGround = new BABYLON.Mesh(name, scene);
  62717. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  62718. vertexData.applyToMesh(tiledGround, options.updatable);
  62719. return tiledGround;
  62720. };
  62721. /**
  62722. * Creates a ground mesh from a height map
  62723. * * The parameter `url` sets the URL of the height map image resource.
  62724. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  62725. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  62726. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  62727. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  62728. * * 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.
  62729. * * 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).
  62730. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62731. * @param name defines the name of the mesh
  62732. * @param url defines the url to the height map
  62733. * @param options defines the options used to create the mesh
  62734. * @param scene defines the hosting scene
  62735. * @returns the ground mesh
  62736. * @see http://doc.babylonjs.com/babylon101/height_map
  62737. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  62738. */
  62739. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  62740. var width = options.width || 10.0;
  62741. var height = options.height || 10.0;
  62742. var subdivisions = options.subdivisions || 1 | 0;
  62743. var minHeight = options.minHeight || 0.0;
  62744. var maxHeight = options.maxHeight || 1.0;
  62745. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  62746. var updatable = options.updatable;
  62747. var onReady = options.onReady;
  62748. var ground = new BABYLON.GroundMesh(name, scene);
  62749. ground._subdivisionsX = subdivisions;
  62750. ground._subdivisionsY = subdivisions;
  62751. ground._width = width;
  62752. ground._height = height;
  62753. ground._maxX = ground._width / 2.0;
  62754. ground._maxZ = ground._height / 2.0;
  62755. ground._minX = -ground._maxX;
  62756. ground._minZ = -ground._maxZ;
  62757. ground._setReady(false);
  62758. var onload = function (img) {
  62759. // Getting height map data
  62760. var canvas = document.createElement("canvas");
  62761. var context = canvas.getContext("2d");
  62762. if (!context) {
  62763. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  62764. }
  62765. if (scene.isDisposed) {
  62766. return;
  62767. }
  62768. var bufferWidth = img.width;
  62769. var bufferHeight = img.height;
  62770. canvas.width = bufferWidth;
  62771. canvas.height = bufferHeight;
  62772. context.drawImage(img, 0, 0);
  62773. // Create VertexData from map data
  62774. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  62775. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  62776. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  62777. width: width, height: height,
  62778. subdivisions: subdivisions,
  62779. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  62780. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  62781. });
  62782. vertexData.applyToMesh(ground, updatable);
  62783. //execute ready callback, if set
  62784. if (onReady) {
  62785. onReady(ground);
  62786. }
  62787. ground._setReady(true);
  62788. };
  62789. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  62790. return ground;
  62791. };
  62792. /**
  62793. * Creates a polygon mesh
  62794. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  62795. * * 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
  62796. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62797. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62798. * * 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)
  62799. * * Remember you can only change the shape positions, not their number when updating a polygon
  62800. * @param name defines the name of the mesh
  62801. * @param options defines the options used to create the mesh
  62802. * @param scene defines the hosting scene
  62803. * @returns the polygon mesh
  62804. */
  62805. MeshBuilder.CreatePolygon = function (name, options, scene) {
  62806. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62807. var shape = options.shape;
  62808. var holes = options.holes || [];
  62809. var depth = options.depth || 0;
  62810. var contours = [];
  62811. var hole = [];
  62812. for (var i = 0; i < shape.length; i++) {
  62813. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  62814. }
  62815. var epsilon = 0.00000001;
  62816. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  62817. contours.pop();
  62818. }
  62819. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  62820. for (var hNb = 0; hNb < holes.length; hNb++) {
  62821. hole = [];
  62822. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  62823. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  62824. }
  62825. polygonTriangulation.addHole(hole);
  62826. }
  62827. var polygon = polygonTriangulation.build(options.updatable, depth);
  62828. polygon._originalBuilderSideOrientation = options.sideOrientation;
  62829. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  62830. vertexData.applyToMesh(polygon, options.updatable);
  62831. return polygon;
  62832. };
  62833. ;
  62834. /**
  62835. * Creates an extruded polygon mesh, with depth in the Y direction.
  62836. * * 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)
  62837. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62838. * @param name defines the name of the mesh
  62839. * @param options defines the options used to create the mesh
  62840. * @param scene defines the hosting scene
  62841. * @returns the polygon mesh
  62842. */
  62843. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  62844. return MeshBuilder.CreatePolygon(name, options, scene);
  62845. };
  62846. ;
  62847. /**
  62848. * Creates a tube mesh.
  62849. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62850. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  62851. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  62852. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  62853. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  62854. * * 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)
  62855. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  62856. * * 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
  62857. * * 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
  62858. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62859. * * 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
  62860. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62861. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62862. * @param name defines the name of the mesh
  62863. * @param options defines the options used to create the mesh
  62864. * @param scene defines the hosting scene
  62865. * @returns the tube mesh
  62866. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62867. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  62868. */
  62869. MeshBuilder.CreateTube = function (name, options, scene) {
  62870. var path = options.path;
  62871. var instance = options.instance;
  62872. var radius = 1.0;
  62873. if (instance) {
  62874. radius = instance.radius;
  62875. }
  62876. if (options.radius !== undefined) {
  62877. radius = options.radius;
  62878. }
  62879. ;
  62880. var tessellation = options.tessellation || 64 | 0;
  62881. var radiusFunction = options.radiusFunction || null;
  62882. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62883. var invertUV = options.invertUV || false;
  62884. var updatable = options.updatable;
  62885. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62886. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  62887. // tube geometry
  62888. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  62889. var tangents = path3D.getTangents();
  62890. var normals = path3D.getNormals();
  62891. var distances = path3D.getDistances();
  62892. var pi2 = Math.PI * 2;
  62893. var step = pi2 / tessellation * arc;
  62894. var returnRadius = function () { return radius; };
  62895. var radiusFunctionFinal = radiusFunction || returnRadius;
  62896. var circlePath;
  62897. var rad;
  62898. var normal;
  62899. var rotated;
  62900. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62901. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62902. for (var i = 0; i < path.length; i++) {
  62903. rad = radiusFunctionFinal(i, distances[i]); // current radius
  62904. circlePath = Array(); // current circle array
  62905. normal = normals[i]; // current normal
  62906. for (var t = 0; t < tessellation; t++) {
  62907. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  62908. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  62909. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  62910. rotated.scaleInPlace(rad).addInPlace(path[i]);
  62911. circlePath[t] = rotated;
  62912. }
  62913. circlePaths[index] = circlePath;
  62914. index++;
  62915. }
  62916. // cap
  62917. var capPath = function (nbPoints, pathIndex) {
  62918. var pointCap = Array();
  62919. for (var i = 0; i < nbPoints; i++) {
  62920. pointCap.push(path[pathIndex]);
  62921. }
  62922. return pointCap;
  62923. };
  62924. switch (cap) {
  62925. case BABYLON.Mesh.NO_CAP:
  62926. break;
  62927. case BABYLON.Mesh.CAP_START:
  62928. circlePaths[0] = capPath(tessellation, 0);
  62929. circlePaths[1] = circlePaths[2].slice(0);
  62930. break;
  62931. case BABYLON.Mesh.CAP_END:
  62932. circlePaths[index] = circlePaths[index - 1].slice(0);
  62933. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62934. break;
  62935. case BABYLON.Mesh.CAP_ALL:
  62936. circlePaths[0] = capPath(tessellation, 0);
  62937. circlePaths[1] = circlePaths[2].slice(0);
  62938. circlePaths[index] = circlePaths[index - 1].slice(0);
  62939. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62940. break;
  62941. default:
  62942. break;
  62943. }
  62944. return circlePaths;
  62945. };
  62946. var path3D;
  62947. var pathArray;
  62948. if (instance) { // tube update
  62949. var arc = options.arc || instance.arc;
  62950. path3D = (instance.path3D).update(path);
  62951. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  62952. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  62953. instance.path3D = path3D;
  62954. instance.pathArray = pathArray;
  62955. instance.arc = arc;
  62956. instance.radius = radius;
  62957. return instance;
  62958. }
  62959. // tube creation
  62960. path3D = new BABYLON.Path3D(path);
  62961. var newPathArray = new Array();
  62962. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62963. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62964. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62965. tube.pathArray = pathArray;
  62966. tube.path3D = path3D;
  62967. tube.tessellation = tessellation;
  62968. tube.cap = cap;
  62969. tube.arc = options.arc;
  62970. tube.radius = radius;
  62971. return tube;
  62972. };
  62973. /**
  62974. * Creates a polyhedron mesh
  62975. * * 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
  62976. * * The parameter `size` (positive float, default 1) sets the polygon size
  62977. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62978. * * 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`
  62979. * * 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
  62980. * * 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)`)
  62981. * * 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
  62982. * * 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
  62983. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62984. * * 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
  62985. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62986. * @param name defines the name of the mesh
  62987. * @param options defines the options used to create the mesh
  62988. * @param scene defines the hosting scene
  62989. * @returns the polyhedron mesh
  62990. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62991. */
  62992. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62993. var polyhedron = new BABYLON.Mesh(name, scene);
  62994. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62995. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62996. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62997. vertexData.applyToMesh(polyhedron, options.updatable);
  62998. return polyhedron;
  62999. };
  63000. /**
  63001. * Creates a decal mesh.
  63002. * 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
  63003. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  63004. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  63005. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  63006. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  63007. * @param name defines the name of the mesh
  63008. * @param sourceMesh defines the mesh where the decal must be applied
  63009. * @param options defines the options used to create the mesh
  63010. * @param scene defines the hosting scene
  63011. * @returns the decal mesh
  63012. * @see http://doc.babylonjs.com/how_to/decals
  63013. */
  63014. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  63015. var indices = sourceMesh.getIndices();
  63016. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63017. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63018. var position = options.position || BABYLON.Vector3.Zero();
  63019. var normal = options.normal || BABYLON.Vector3.Up();
  63020. var size = options.size || BABYLON.Vector3.One();
  63021. var angle = options.angle || 0;
  63022. // Getting correct rotation
  63023. if (!normal) {
  63024. var target = new BABYLON.Vector3(0, 0, 1);
  63025. var camera = sourceMesh.getScene().activeCamera;
  63026. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63027. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63028. }
  63029. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63030. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63031. var pitch = Math.atan2(normal.y, len);
  63032. // Matrix
  63033. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63034. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63035. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63036. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63037. var vertexData = new BABYLON.VertexData();
  63038. vertexData.indices = [];
  63039. vertexData.positions = [];
  63040. vertexData.normals = [];
  63041. vertexData.uvs = [];
  63042. var currentVertexDataIndex = 0;
  63043. var extractDecalVector3 = function (indexId) {
  63044. var result = new BABYLON.PositionNormalVertex();
  63045. if (!indices || !positions || !normals) {
  63046. return result;
  63047. }
  63048. var vertexId = indices[indexId];
  63049. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63050. // Send vector to decal local world
  63051. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63052. // Get normal
  63053. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63054. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63055. return result;
  63056. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63057. var clip = function (vertices, axis) {
  63058. if (vertices.length === 0) {
  63059. return vertices;
  63060. }
  63061. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63062. var clipVertices = function (v0, v1) {
  63063. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63064. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63065. };
  63066. var result = new Array();
  63067. for (var index = 0; index < vertices.length; index += 3) {
  63068. var v1Out;
  63069. var v2Out;
  63070. var v3Out;
  63071. var total = 0;
  63072. var nV1 = null;
  63073. var nV2 = null;
  63074. var nV3 = null;
  63075. var nV4 = null;
  63076. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63077. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63078. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63079. v1Out = d1 > 0;
  63080. v2Out = d2 > 0;
  63081. v3Out = d3 > 0;
  63082. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63083. switch (total) {
  63084. case 0:
  63085. result.push(vertices[index]);
  63086. result.push(vertices[index + 1]);
  63087. result.push(vertices[index + 2]);
  63088. break;
  63089. case 1:
  63090. if (v1Out) {
  63091. nV1 = vertices[index + 1];
  63092. nV2 = vertices[index + 2];
  63093. nV3 = clipVertices(vertices[index], nV1);
  63094. nV4 = clipVertices(vertices[index], nV2);
  63095. }
  63096. if (v2Out) {
  63097. nV1 = vertices[index];
  63098. nV2 = vertices[index + 2];
  63099. nV3 = clipVertices(vertices[index + 1], nV1);
  63100. nV4 = clipVertices(vertices[index + 1], nV2);
  63101. result.push(nV3);
  63102. result.push(nV2.clone());
  63103. result.push(nV1.clone());
  63104. result.push(nV2.clone());
  63105. result.push(nV3.clone());
  63106. result.push(nV4);
  63107. break;
  63108. }
  63109. if (v3Out) {
  63110. nV1 = vertices[index];
  63111. nV2 = vertices[index + 1];
  63112. nV3 = clipVertices(vertices[index + 2], nV1);
  63113. nV4 = clipVertices(vertices[index + 2], nV2);
  63114. }
  63115. if (nV1 && nV2 && nV3 && nV4) {
  63116. result.push(nV1.clone());
  63117. result.push(nV2.clone());
  63118. result.push(nV3);
  63119. result.push(nV4);
  63120. result.push(nV3.clone());
  63121. result.push(nV2.clone());
  63122. }
  63123. break;
  63124. case 2:
  63125. if (!v1Out) {
  63126. nV1 = vertices[index].clone();
  63127. nV2 = clipVertices(nV1, vertices[index + 1]);
  63128. nV3 = clipVertices(nV1, vertices[index + 2]);
  63129. result.push(nV1);
  63130. result.push(nV2);
  63131. result.push(nV3);
  63132. }
  63133. if (!v2Out) {
  63134. nV1 = vertices[index + 1].clone();
  63135. nV2 = clipVertices(nV1, vertices[index + 2]);
  63136. nV3 = clipVertices(nV1, vertices[index]);
  63137. result.push(nV1);
  63138. result.push(nV2);
  63139. result.push(nV3);
  63140. }
  63141. if (!v3Out) {
  63142. nV1 = vertices[index + 2].clone();
  63143. nV2 = clipVertices(nV1, vertices[index]);
  63144. nV3 = clipVertices(nV1, vertices[index + 1]);
  63145. result.push(nV1);
  63146. result.push(nV2);
  63147. result.push(nV3);
  63148. }
  63149. break;
  63150. case 3:
  63151. break;
  63152. }
  63153. }
  63154. return result;
  63155. };
  63156. for (var index = 0; index < indices.length; index += 3) {
  63157. var faceVertices = new Array();
  63158. faceVertices.push(extractDecalVector3(index));
  63159. faceVertices.push(extractDecalVector3(index + 1));
  63160. faceVertices.push(extractDecalVector3(index + 2));
  63161. // Clip
  63162. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  63163. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  63164. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  63165. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  63166. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  63167. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  63168. if (faceVertices.length === 0) {
  63169. continue;
  63170. }
  63171. // Add UVs and get back to world
  63172. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  63173. var vertex = faceVertices[vIndex];
  63174. //TODO check for Int32Array | Uint32Array | Uint16Array
  63175. vertexData.indices.push(currentVertexDataIndex);
  63176. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  63177. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  63178. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  63179. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  63180. currentVertexDataIndex++;
  63181. }
  63182. }
  63183. // Return mesh
  63184. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  63185. vertexData.applyToMesh(decal);
  63186. decal.position = position.clone();
  63187. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  63188. return decal;
  63189. };
  63190. // Privates
  63191. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  63192. // extrusion geometry
  63193. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  63194. var tangents = path3D.getTangents();
  63195. var normals = path3D.getNormals();
  63196. var binormals = path3D.getBinormals();
  63197. var distances = path3D.getDistances();
  63198. var angle = 0;
  63199. var returnScale = function () { return scale !== null ? scale : 1; };
  63200. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  63201. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  63202. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  63203. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63204. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63205. for (var i = 0; i < curve.length; i++) {
  63206. var shapePath = new Array();
  63207. var angleStep = rotate(i, distances[i]);
  63208. var scaleRatio = scl(i, distances[i]);
  63209. for (var p = 0; p < shape.length; p++) {
  63210. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  63211. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  63212. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  63213. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  63214. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  63215. shapePath[p] = rotated;
  63216. }
  63217. shapePaths[index] = shapePath;
  63218. angle += angleStep;
  63219. index++;
  63220. }
  63221. // cap
  63222. var capPath = function (shapePath) {
  63223. var pointCap = Array();
  63224. var barycenter = BABYLON.Vector3.Zero();
  63225. var i;
  63226. for (i = 0; i < shapePath.length; i++) {
  63227. barycenter.addInPlace(shapePath[i]);
  63228. }
  63229. barycenter.scaleInPlace(1.0 / shapePath.length);
  63230. for (i = 0; i < shapePath.length; i++) {
  63231. pointCap.push(barycenter);
  63232. }
  63233. return pointCap;
  63234. };
  63235. switch (cap) {
  63236. case BABYLON.Mesh.NO_CAP:
  63237. break;
  63238. case BABYLON.Mesh.CAP_START:
  63239. shapePaths[0] = capPath(shapePaths[2]);
  63240. shapePaths[1] = shapePaths[2];
  63241. break;
  63242. case BABYLON.Mesh.CAP_END:
  63243. shapePaths[index] = shapePaths[index - 1];
  63244. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63245. break;
  63246. case BABYLON.Mesh.CAP_ALL:
  63247. shapePaths[0] = capPath(shapePaths[2]);
  63248. shapePaths[1] = shapePaths[2];
  63249. shapePaths[index] = shapePaths[index - 1];
  63250. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63251. break;
  63252. default:
  63253. break;
  63254. }
  63255. return shapePaths;
  63256. };
  63257. var path3D;
  63258. var pathArray;
  63259. if (instance) { // instance update
  63260. path3D = (instance.path3D).update(curve);
  63261. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  63262. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  63263. return instance;
  63264. }
  63265. // extruded shape creation
  63266. path3D = new BABYLON.Path3D(curve);
  63267. var newShapePaths = new Array();
  63268. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63269. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  63270. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  63271. extrudedGeneric.pathArray = pathArray;
  63272. extrudedGeneric.path3D = path3D;
  63273. extrudedGeneric.cap = cap;
  63274. return extrudedGeneric;
  63275. };
  63276. return MeshBuilder;
  63277. }());
  63278. BABYLON.MeshBuilder = MeshBuilder;
  63279. })(BABYLON || (BABYLON = {}));
  63280. //# sourceMappingURL=babylon.meshBuilder.js.map
  63281. var BABYLON;
  63282. (function (BABYLON) {
  63283. /**
  63284. * Draco compression (https://google.github.io/draco/)
  63285. *
  63286. * This class wraps the Draco module.
  63287. *
  63288. * **Encoder**
  63289. *
  63290. * The encoder is not currently implemented.
  63291. *
  63292. * **Decoder**
  63293. *
  63294. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  63295. *
  63296. * To update the configuration, use the following code:
  63297. * ```javascript
  63298. * BABYLON.DracoCompression.Configuration = {
  63299. * decoder: {
  63300. * wasmUrl: "<url to the WebAssembly library>",
  63301. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  63302. * fallbackUrl: "<url to the fallback JavaScript library>",
  63303. * }
  63304. * };
  63305. * ```
  63306. *
  63307. * 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.
  63308. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  63309. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  63310. *
  63311. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  63312. * ```javascript
  63313. * var dracoCompression = new BABYLON.DracoCompression();
  63314. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  63315. * [BABYLON.VertexBuffer.PositionKind]: 0
  63316. * });
  63317. * ```
  63318. *
  63319. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  63320. */
  63321. var DracoCompression = /** @class */ (function () {
  63322. /**
  63323. * Constructor
  63324. */
  63325. function DracoCompression() {
  63326. }
  63327. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  63328. /**
  63329. * Returns true if the decoder is available.
  63330. */
  63331. get: function () {
  63332. if (typeof DracoDecoderModule !== "undefined") {
  63333. return true;
  63334. }
  63335. var decoder = DracoCompression.Configuration.decoder;
  63336. if (decoder) {
  63337. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63338. return true;
  63339. }
  63340. if (decoder.fallbackUrl) {
  63341. return true;
  63342. }
  63343. }
  63344. return false;
  63345. },
  63346. enumerable: true,
  63347. configurable: true
  63348. });
  63349. /**
  63350. * Stop all async operations and release resources.
  63351. */
  63352. DracoCompression.prototype.dispose = function () {
  63353. };
  63354. /**
  63355. * Decode Draco compressed mesh data to vertex data.
  63356. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  63357. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  63358. * @returns A promise that resolves with the decoded vertex data
  63359. */
  63360. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  63361. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  63362. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  63363. var module = wrappedModule.module;
  63364. var vertexData = new BABYLON.VertexData();
  63365. var buffer = new module.DecoderBuffer();
  63366. buffer.Init(dataView, dataView.byteLength);
  63367. var decoder = new module.Decoder();
  63368. var geometry;
  63369. var status;
  63370. try {
  63371. var type = decoder.GetEncodedGeometryType(buffer);
  63372. switch (type) {
  63373. case module.TRIANGULAR_MESH:
  63374. geometry = new module.Mesh();
  63375. status = decoder.DecodeBufferToMesh(buffer, geometry);
  63376. break;
  63377. case module.POINT_CLOUD:
  63378. geometry = new module.PointCloud();
  63379. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  63380. break;
  63381. default:
  63382. throw new Error("Invalid geometry type " + type);
  63383. }
  63384. if (!status.ok() || !geometry.ptr) {
  63385. throw new Error(status.error_msg());
  63386. }
  63387. var numPoints = geometry.num_points();
  63388. if (type === module.TRIANGULAR_MESH) {
  63389. var numFaces = geometry.num_faces();
  63390. var faceIndices = new module.DracoInt32Array();
  63391. try {
  63392. var indices = new Uint32Array(numFaces * 3);
  63393. for (var i = 0; i < numFaces; i++) {
  63394. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  63395. var offset = i * 3;
  63396. indices[offset + 0] = faceIndices.GetValue(0);
  63397. indices[offset + 1] = faceIndices.GetValue(1);
  63398. indices[offset + 2] = faceIndices.GetValue(2);
  63399. }
  63400. vertexData.indices = indices;
  63401. }
  63402. finally {
  63403. module.destroy(faceIndices);
  63404. }
  63405. }
  63406. for (var kind in attributes) {
  63407. var uniqueId = attributes[kind];
  63408. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  63409. var dracoData = new module.DracoFloat32Array();
  63410. try {
  63411. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  63412. var babylonData = new Float32Array(numPoints * attribute.num_components());
  63413. for (var i = 0; i < babylonData.length; i++) {
  63414. babylonData[i] = dracoData.GetValue(i);
  63415. }
  63416. vertexData.set(babylonData, kind);
  63417. }
  63418. finally {
  63419. module.destroy(dracoData);
  63420. }
  63421. }
  63422. }
  63423. finally {
  63424. if (geometry) {
  63425. module.destroy(geometry);
  63426. }
  63427. module.destroy(decoder);
  63428. module.destroy(buffer);
  63429. }
  63430. return vertexData;
  63431. });
  63432. };
  63433. DracoCompression._GetDecoderModule = function () {
  63434. if (!DracoCompression._DecoderModulePromise) {
  63435. var promise = null;
  63436. var config_1 = {};
  63437. if (typeof DracoDecoderModule !== "undefined") {
  63438. promise = Promise.resolve();
  63439. }
  63440. else {
  63441. var decoder = DracoCompression.Configuration.decoder;
  63442. if (decoder) {
  63443. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63444. promise = Promise.all([
  63445. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63446. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63447. config_1.wasmBinary = data;
  63448. })
  63449. ]);
  63450. }
  63451. else if (decoder.fallbackUrl) {
  63452. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63453. }
  63454. }
  63455. }
  63456. if (!promise) {
  63457. throw new Error("Draco decoder module is not available");
  63458. }
  63459. DracoCompression._DecoderModulePromise = promise.then(function () {
  63460. return new Promise(function (resolve) {
  63461. config_1.onModuleLoaded = function (decoderModule) {
  63462. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63463. resolve({ module: decoderModule });
  63464. };
  63465. DracoDecoderModule(config_1);
  63466. });
  63467. });
  63468. }
  63469. return DracoCompression._DecoderModulePromise;
  63470. };
  63471. DracoCompression._LoadScriptAsync = function (url) {
  63472. return new Promise(function (resolve, reject) {
  63473. BABYLON.Tools.LoadScript(url, function () {
  63474. resolve();
  63475. }, function (message) {
  63476. reject(new Error(message));
  63477. });
  63478. });
  63479. };
  63480. DracoCompression._LoadFileAsync = function (url) {
  63481. return new Promise(function (resolve, reject) {
  63482. BABYLON.Tools.LoadFile(url, function (data) {
  63483. resolve(data);
  63484. }, undefined, undefined, true, function (request, exception) {
  63485. reject(exception);
  63486. });
  63487. });
  63488. };
  63489. /**
  63490. * The configuration. Defaults to the following urls:
  63491. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63492. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63493. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63494. */
  63495. DracoCompression.Configuration = {
  63496. decoder: {
  63497. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63498. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63499. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63500. }
  63501. };
  63502. return DracoCompression;
  63503. }());
  63504. BABYLON.DracoCompression = DracoCompression;
  63505. })(BABYLON || (BABYLON = {}));
  63506. //# sourceMappingURL=babylon.dracoCompression.js.map
  63507. var BABYLON;
  63508. (function (BABYLON) {
  63509. var AudioEngine = /** @class */ (function () {
  63510. function AudioEngine() {
  63511. this._audioContext = null;
  63512. this._audioContextInitialized = false;
  63513. this.canUseWebAudio = false;
  63514. this.WarnedWebAudioUnsupported = false;
  63515. this.unlocked = false;
  63516. this.isMP3supported = false;
  63517. this.isOGGsupported = false;
  63518. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63519. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63520. this.canUseWebAudio = true;
  63521. }
  63522. var audioElem = document.createElement('audio');
  63523. try {
  63524. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63525. this.isMP3supported = true;
  63526. }
  63527. }
  63528. catch (e) {
  63529. // protect error during capability check.
  63530. }
  63531. try {
  63532. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63533. this.isOGGsupported = true;
  63534. }
  63535. }
  63536. catch (e) {
  63537. // protect error during capability check.
  63538. }
  63539. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63540. this._unlockiOSaudio();
  63541. }
  63542. else {
  63543. this.unlocked = true;
  63544. }
  63545. }
  63546. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63547. get: function () {
  63548. if (!this._audioContextInitialized) {
  63549. this._initializeAudioContext();
  63550. }
  63551. return this._audioContext;
  63552. },
  63553. enumerable: true,
  63554. configurable: true
  63555. });
  63556. AudioEngine.prototype._unlockiOSaudio = function () {
  63557. var _this = this;
  63558. var unlockaudio = function () {
  63559. if (!_this.audioContext) {
  63560. return;
  63561. }
  63562. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63563. var source = _this.audioContext.createBufferSource();
  63564. source.buffer = buffer;
  63565. source.connect(_this.audioContext.destination);
  63566. source.start(0);
  63567. setTimeout(function () {
  63568. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  63569. _this.unlocked = true;
  63570. window.removeEventListener('touchend', unlockaudio, false);
  63571. if (_this.onAudioUnlocked) {
  63572. _this.onAudioUnlocked();
  63573. }
  63574. }
  63575. }, 0);
  63576. };
  63577. window.addEventListener('touchend', unlockaudio, false);
  63578. };
  63579. AudioEngine.prototype._initializeAudioContext = function () {
  63580. try {
  63581. if (this.canUseWebAudio) {
  63582. this._audioContext = new AudioContext();
  63583. // create a global volume gain node
  63584. this.masterGain = this._audioContext.createGain();
  63585. this.masterGain.gain.value = 1;
  63586. this.masterGain.connect(this._audioContext.destination);
  63587. this._audioContextInitialized = true;
  63588. }
  63589. }
  63590. catch (e) {
  63591. this.canUseWebAudio = false;
  63592. BABYLON.Tools.Error("Web Audio: " + e.message);
  63593. }
  63594. };
  63595. AudioEngine.prototype.dispose = function () {
  63596. if (this.canUseWebAudio && this._audioContextInitialized) {
  63597. if (this._connectedAnalyser && this._audioContext) {
  63598. this._connectedAnalyser.stopDebugCanvas();
  63599. this._connectedAnalyser.dispose();
  63600. this.masterGain.disconnect();
  63601. this.masterGain.connect(this._audioContext.destination);
  63602. this._connectedAnalyser = null;
  63603. }
  63604. this.masterGain.gain.value = 1;
  63605. }
  63606. this.WarnedWebAudioUnsupported = false;
  63607. };
  63608. AudioEngine.prototype.getGlobalVolume = function () {
  63609. if (this.canUseWebAudio && this._audioContextInitialized) {
  63610. return this.masterGain.gain.value;
  63611. }
  63612. else {
  63613. return -1;
  63614. }
  63615. };
  63616. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  63617. if (this.canUseWebAudio && this._audioContextInitialized) {
  63618. this.masterGain.gain.value = newVolume;
  63619. }
  63620. };
  63621. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  63622. if (this._connectedAnalyser) {
  63623. this._connectedAnalyser.stopDebugCanvas();
  63624. }
  63625. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  63626. this._connectedAnalyser = analyser;
  63627. this.masterGain.disconnect();
  63628. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  63629. }
  63630. };
  63631. return AudioEngine;
  63632. }());
  63633. BABYLON.AudioEngine = AudioEngine;
  63634. })(BABYLON || (BABYLON = {}));
  63635. //# sourceMappingURL=babylon.audioEngine.js.map
  63636. var BABYLON;
  63637. (function (BABYLON) {
  63638. var Sound = /** @class */ (function () {
  63639. /**
  63640. * Create a sound and attach it to a scene
  63641. * @param name Name of your sound
  63642. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  63643. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  63644. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  63645. */
  63646. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  63647. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  63648. var _this = this;
  63649. this.autoplay = false;
  63650. this.loop = false;
  63651. this.useCustomAttenuation = false;
  63652. this.spatialSound = false;
  63653. this.refDistance = 1;
  63654. this.rolloffFactor = 1;
  63655. this.maxDistance = 100;
  63656. this.distanceModel = "linear";
  63657. this._panningModel = "equalpower";
  63658. this._playbackRate = 1;
  63659. this._streaming = false;
  63660. this._startTime = 0;
  63661. this._startOffset = 0;
  63662. this._position = BABYLON.Vector3.Zero();
  63663. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  63664. this._volume = 1;
  63665. this._isReadyToPlay = false;
  63666. this.isPlaying = false;
  63667. this.isPaused = false;
  63668. this._isDirectional = false;
  63669. // Used if you'd like to create a directional sound.
  63670. // If not set, the sound will be omnidirectional
  63671. this._coneInnerAngle = 360;
  63672. this._coneOuterAngle = 360;
  63673. this._coneOuterGain = 0;
  63674. this._isOutputConnected = false;
  63675. this._urlType = "Unknown";
  63676. this.name = name;
  63677. this._scene = scene;
  63678. this._readyToPlayCallback = readyToPlayCallback;
  63679. // Default custom attenuation function is a linear attenuation
  63680. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  63681. if (currentDistance < maxDistance) {
  63682. return currentVolume * (1 - currentDistance / maxDistance);
  63683. }
  63684. else {
  63685. return 0;
  63686. }
  63687. };
  63688. if (options) {
  63689. this.autoplay = options.autoplay || false;
  63690. this.loop = options.loop || false;
  63691. // if volume === 0, we need another way to check this option
  63692. if (options.volume !== undefined) {
  63693. this._volume = options.volume;
  63694. }
  63695. this.spatialSound = options.spatialSound || false;
  63696. this.maxDistance = options.maxDistance || 100;
  63697. this.useCustomAttenuation = options.useCustomAttenuation || false;
  63698. this.rolloffFactor = options.rolloffFactor || 1;
  63699. this.refDistance = options.refDistance || 1;
  63700. this.distanceModel = options.distanceModel || "linear";
  63701. this._playbackRate = options.playbackRate || 1;
  63702. this._streaming = options.streaming || false;
  63703. }
  63704. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63705. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  63706. this._soundGain.gain.value = this._volume;
  63707. this._inputAudioNode = this._soundGain;
  63708. this._ouputAudioNode = this._soundGain;
  63709. if (this.spatialSound) {
  63710. this._createSpatialParameters();
  63711. }
  63712. this._scene.mainSoundTrack.AddSound(this);
  63713. var validParameter = true;
  63714. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  63715. if (urlOrArrayBuffer) {
  63716. try {
  63717. if (typeof (urlOrArrayBuffer) === "string") {
  63718. this._urlType = "String";
  63719. }
  63720. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  63721. this._urlType = "ArrayBuffer";
  63722. }
  63723. else if (urlOrArrayBuffer instanceof MediaStream) {
  63724. this._urlType = "MediaStream";
  63725. }
  63726. else if (Array.isArray(urlOrArrayBuffer)) {
  63727. this._urlType = "Array";
  63728. }
  63729. var urls = [];
  63730. var codecSupportedFound = false;
  63731. switch (this._urlType) {
  63732. case "MediaStream":
  63733. this._streaming = true;
  63734. this._isReadyToPlay = true;
  63735. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  63736. if (this.autoplay) {
  63737. this.play();
  63738. }
  63739. if (this._readyToPlayCallback) {
  63740. this._readyToPlayCallback();
  63741. }
  63742. break;
  63743. case "ArrayBuffer":
  63744. if (urlOrArrayBuffer.byteLength > 0) {
  63745. codecSupportedFound = true;
  63746. this._soundLoaded(urlOrArrayBuffer);
  63747. }
  63748. break;
  63749. case "String":
  63750. urls.push(urlOrArrayBuffer);
  63751. case "Array":
  63752. if (urls.length === 0)
  63753. urls = urlOrArrayBuffer;
  63754. // If we found a supported format, we load it immediately and stop the loop
  63755. for (var i = 0; i < urls.length; i++) {
  63756. var url = urls[i];
  63757. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  63758. codecSupportedFound = true;
  63759. }
  63760. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  63761. codecSupportedFound = true;
  63762. }
  63763. if (url.indexOf(".wav", url.length - 4) !== -1) {
  63764. codecSupportedFound = true;
  63765. }
  63766. if (url.indexOf("blob:") !== -1) {
  63767. codecSupportedFound = true;
  63768. }
  63769. if (codecSupportedFound) {
  63770. // Loading sound using XHR2
  63771. if (!this._streaming) {
  63772. this._scene._loadFile(url, function (data) {
  63773. _this._soundLoaded(data);
  63774. }, undefined, true, true, function (exception) {
  63775. if (exception) {
  63776. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  63777. }
  63778. BABYLON.Tools.Error("Sound creation aborted.");
  63779. _this._scene.mainSoundTrack.RemoveSound(_this);
  63780. });
  63781. }
  63782. // Streaming sound using HTML5 Audio tag
  63783. else {
  63784. this._htmlAudioElement = new Audio(url);
  63785. this._htmlAudioElement.controls = false;
  63786. this._htmlAudioElement.loop = this.loop;
  63787. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  63788. this._htmlAudioElement.preload = "auto";
  63789. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  63790. _this._isReadyToPlay = true;
  63791. if (_this.autoplay) {
  63792. _this.play();
  63793. }
  63794. if (_this._readyToPlayCallback) {
  63795. _this._readyToPlayCallback();
  63796. }
  63797. });
  63798. document.body.appendChild(this._htmlAudioElement);
  63799. }
  63800. break;
  63801. }
  63802. }
  63803. break;
  63804. default:
  63805. validParameter = false;
  63806. break;
  63807. }
  63808. if (!validParameter) {
  63809. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  63810. }
  63811. else {
  63812. if (!codecSupportedFound) {
  63813. this._isReadyToPlay = true;
  63814. // Simulating a ready to play event to avoid breaking code path
  63815. if (this._readyToPlayCallback) {
  63816. window.setTimeout(function () {
  63817. if (_this._readyToPlayCallback) {
  63818. _this._readyToPlayCallback();
  63819. }
  63820. }, 1000);
  63821. }
  63822. }
  63823. }
  63824. }
  63825. catch (ex) {
  63826. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  63827. this._scene.mainSoundTrack.RemoveSound(this);
  63828. }
  63829. }
  63830. }
  63831. else {
  63832. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  63833. this._scene.mainSoundTrack.AddSound(this);
  63834. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  63835. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  63836. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  63837. }
  63838. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  63839. if (this._readyToPlayCallback) {
  63840. window.setTimeout(function () {
  63841. if (_this._readyToPlayCallback) {
  63842. _this._readyToPlayCallback();
  63843. }
  63844. }, 1000);
  63845. }
  63846. }
  63847. }
  63848. Sound.prototype.dispose = function () {
  63849. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63850. if (this.isPlaying) {
  63851. this.stop();
  63852. }
  63853. this._isReadyToPlay = false;
  63854. if (this.soundTrackId === -1) {
  63855. this._scene.mainSoundTrack.RemoveSound(this);
  63856. }
  63857. else {
  63858. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  63859. }
  63860. if (this._soundGain) {
  63861. this._soundGain.disconnect();
  63862. this._soundGain = null;
  63863. }
  63864. if (this._soundPanner) {
  63865. this._soundPanner.disconnect();
  63866. this._soundPanner = null;
  63867. }
  63868. if (this._soundSource) {
  63869. this._soundSource.disconnect();
  63870. this._soundSource = null;
  63871. }
  63872. this._audioBuffer = null;
  63873. if (this._htmlAudioElement) {
  63874. this._htmlAudioElement.pause();
  63875. this._htmlAudioElement.src = "";
  63876. document.body.removeChild(this._htmlAudioElement);
  63877. }
  63878. if (this._streamingSource) {
  63879. this._streamingSource.disconnect();
  63880. }
  63881. if (this._connectedMesh && this._registerFunc) {
  63882. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63883. this._connectedMesh = null;
  63884. }
  63885. }
  63886. };
  63887. Sound.prototype.isReady = function () {
  63888. return this._isReadyToPlay;
  63889. };
  63890. Sound.prototype._soundLoaded = function (audioData) {
  63891. var _this = this;
  63892. if (!BABYLON.Engine.audioEngine.audioContext) {
  63893. return;
  63894. }
  63895. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  63896. _this._audioBuffer = buffer;
  63897. _this._isReadyToPlay = true;
  63898. if (_this.autoplay) {
  63899. _this.play();
  63900. }
  63901. if (_this._readyToPlayCallback) {
  63902. _this._readyToPlayCallback();
  63903. }
  63904. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  63905. };
  63906. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  63907. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63908. this._audioBuffer = audioBuffer;
  63909. this._isReadyToPlay = true;
  63910. }
  63911. };
  63912. Sound.prototype.updateOptions = function (options) {
  63913. if (options) {
  63914. this.loop = options.loop || this.loop;
  63915. this.maxDistance = options.maxDistance || this.maxDistance;
  63916. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  63917. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  63918. this.refDistance = options.refDistance || this.refDistance;
  63919. this.distanceModel = options.distanceModel || this.distanceModel;
  63920. this._playbackRate = options.playbackRate || this._playbackRate;
  63921. this._updateSpatialParameters();
  63922. if (this.isPlaying) {
  63923. if (this._streaming && this._htmlAudioElement) {
  63924. this._htmlAudioElement.playbackRate = this._playbackRate;
  63925. }
  63926. else {
  63927. if (this._soundSource) {
  63928. this._soundSource.playbackRate.value = this._playbackRate;
  63929. }
  63930. }
  63931. }
  63932. }
  63933. };
  63934. Sound.prototype._createSpatialParameters = function () {
  63935. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63936. if (this._scene.headphone) {
  63937. this._panningModel = "HRTF";
  63938. }
  63939. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  63940. this._updateSpatialParameters();
  63941. this._soundPanner.connect(this._ouputAudioNode);
  63942. this._inputAudioNode = this._soundPanner;
  63943. }
  63944. };
  63945. Sound.prototype._updateSpatialParameters = function () {
  63946. if (this.spatialSound && this._soundPanner) {
  63947. if (this.useCustomAttenuation) {
  63948. // Tricks to disable in a way embedded Web Audio attenuation
  63949. this._soundPanner.distanceModel = "linear";
  63950. this._soundPanner.maxDistance = Number.MAX_VALUE;
  63951. this._soundPanner.refDistance = 1;
  63952. this._soundPanner.rolloffFactor = 1;
  63953. this._soundPanner.panningModel = this._panningModel;
  63954. }
  63955. else {
  63956. this._soundPanner.distanceModel = this.distanceModel;
  63957. this._soundPanner.maxDistance = this.maxDistance;
  63958. this._soundPanner.refDistance = this.refDistance;
  63959. this._soundPanner.rolloffFactor = this.rolloffFactor;
  63960. this._soundPanner.panningModel = this._panningModel;
  63961. }
  63962. }
  63963. };
  63964. Sound.prototype.switchPanningModelToHRTF = function () {
  63965. this._panningModel = "HRTF";
  63966. this._switchPanningModel();
  63967. };
  63968. Sound.prototype.switchPanningModelToEqualPower = function () {
  63969. this._panningModel = "equalpower";
  63970. this._switchPanningModel();
  63971. };
  63972. Sound.prototype._switchPanningModel = function () {
  63973. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63974. this._soundPanner.panningModel = this._panningModel;
  63975. }
  63976. };
  63977. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  63978. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63979. if (this._isOutputConnected) {
  63980. this._ouputAudioNode.disconnect();
  63981. }
  63982. this._ouputAudioNode.connect(soundTrackAudioNode);
  63983. this._isOutputConnected = true;
  63984. }
  63985. };
  63986. /**
  63987. * Transform this sound into a directional source
  63988. * @param coneInnerAngle Size of the inner cone in degree
  63989. * @param coneOuterAngle Size of the outer cone in degree
  63990. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63991. */
  63992. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63993. if (coneOuterAngle < coneInnerAngle) {
  63994. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63995. return;
  63996. }
  63997. this._coneInnerAngle = coneInnerAngle;
  63998. this._coneOuterAngle = coneOuterAngle;
  63999. this._coneOuterGain = coneOuterGain;
  64000. this._isDirectional = true;
  64001. if (this.isPlaying && this.loop) {
  64002. this.stop();
  64003. this.play();
  64004. }
  64005. };
  64006. Sound.prototype.setPosition = function (newPosition) {
  64007. this._position = newPosition;
  64008. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64009. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64010. }
  64011. };
  64012. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  64013. this._localDirection = newLocalDirection;
  64014. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  64015. this._updateDirection();
  64016. }
  64017. };
  64018. Sound.prototype._updateDirection = function () {
  64019. if (!this._connectedMesh || !this._soundPanner) {
  64020. return;
  64021. }
  64022. var mat = this._connectedMesh.getWorldMatrix();
  64023. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  64024. direction.normalize();
  64025. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  64026. };
  64027. Sound.prototype.updateDistanceFromListener = function () {
  64028. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  64029. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64030. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64031. }
  64032. };
  64033. Sound.prototype.setAttenuationFunction = function (callback) {
  64034. this._customAttenuationFunction = callback;
  64035. };
  64036. /**
  64037. * Play the sound
  64038. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64039. * @param offset (optional) Start the sound setting it at a specific time
  64040. */
  64041. Sound.prototype.play = function (time, offset) {
  64042. var _this = this;
  64043. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  64044. try {
  64045. if (this._startOffset < 0) {
  64046. time = -this._startOffset;
  64047. this._startOffset = 0;
  64048. }
  64049. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64050. if (!this._soundSource || !this._streamingSource) {
  64051. if (this.spatialSound && this._soundPanner) {
  64052. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64053. if (this._isDirectional) {
  64054. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64055. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64056. this._soundPanner.coneOuterGain = this._coneOuterGain;
  64057. if (this._connectedMesh) {
  64058. this._updateDirection();
  64059. }
  64060. else {
  64061. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  64062. }
  64063. }
  64064. }
  64065. }
  64066. if (this._streaming) {
  64067. if (!this._streamingSource) {
  64068. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  64069. this._htmlAudioElement.onended = function () { _this._onended(); };
  64070. this._htmlAudioElement.playbackRate = this._playbackRate;
  64071. }
  64072. this._streamingSource.disconnect();
  64073. this._streamingSource.connect(this._inputAudioNode);
  64074. if (this._htmlAudioElement) {
  64075. this._htmlAudioElement.play();
  64076. }
  64077. }
  64078. else {
  64079. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  64080. this._soundSource.buffer = this._audioBuffer;
  64081. this._soundSource.connect(this._inputAudioNode);
  64082. this._soundSource.loop = this.loop;
  64083. this._soundSource.playbackRate.value = this._playbackRate;
  64084. this._soundSource.onended = function () { _this._onended(); };
  64085. if (this._soundSource.buffer) {
  64086. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  64087. }
  64088. }
  64089. this._startTime = startTime;
  64090. this.isPlaying = true;
  64091. this.isPaused = false;
  64092. }
  64093. catch (ex) {
  64094. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  64095. }
  64096. }
  64097. };
  64098. Sound.prototype._onended = function () {
  64099. this.isPlaying = false;
  64100. if (this.onended) {
  64101. this.onended();
  64102. }
  64103. };
  64104. /**
  64105. * Stop the sound
  64106. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  64107. */
  64108. Sound.prototype.stop = function (time) {
  64109. if (this.isPlaying) {
  64110. if (this._streaming) {
  64111. if (this._htmlAudioElement) {
  64112. this._htmlAudioElement.pause();
  64113. // Test needed for Firefox or it will generate an Invalid State Error
  64114. if (this._htmlAudioElement.currentTime > 0) {
  64115. this._htmlAudioElement.currentTime = 0;
  64116. }
  64117. }
  64118. else {
  64119. this._streamingSource.disconnect();
  64120. }
  64121. }
  64122. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  64123. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64124. this._soundSource.stop(stopTime);
  64125. this._soundSource.onended = function () { };
  64126. if (!this.isPaused) {
  64127. this._startOffset = 0;
  64128. }
  64129. }
  64130. this.isPlaying = false;
  64131. }
  64132. };
  64133. Sound.prototype.pause = function () {
  64134. if (this.isPlaying) {
  64135. this.isPaused = true;
  64136. if (this._streaming) {
  64137. if (this._htmlAudioElement) {
  64138. this._htmlAudioElement.pause();
  64139. }
  64140. else {
  64141. this._streamingSource.disconnect();
  64142. }
  64143. }
  64144. else if (BABYLON.Engine.audioEngine.audioContext) {
  64145. this.stop(0);
  64146. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  64147. }
  64148. }
  64149. };
  64150. Sound.prototype.setVolume = function (newVolume, time) {
  64151. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  64152. if (time && BABYLON.Engine.audioEngine.audioContext) {
  64153. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  64154. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  64155. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  64156. }
  64157. else {
  64158. this._soundGain.gain.value = newVolume;
  64159. }
  64160. }
  64161. this._volume = newVolume;
  64162. };
  64163. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  64164. this._playbackRate = newPlaybackRate;
  64165. if (this.isPlaying) {
  64166. if (this._streaming && this._htmlAudioElement) {
  64167. this._htmlAudioElement.playbackRate = this._playbackRate;
  64168. }
  64169. else if (this._soundSource) {
  64170. this._soundSource.playbackRate.value = this._playbackRate;
  64171. }
  64172. }
  64173. };
  64174. Sound.prototype.getVolume = function () {
  64175. return this._volume;
  64176. };
  64177. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  64178. var _this = this;
  64179. if (this._connectedMesh && this._registerFunc) {
  64180. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64181. this._registerFunc = null;
  64182. }
  64183. this._connectedMesh = meshToConnectTo;
  64184. if (!this.spatialSound) {
  64185. this.spatialSound = true;
  64186. this._createSpatialParameters();
  64187. if (this.isPlaying && this.loop) {
  64188. this.stop();
  64189. this.play();
  64190. }
  64191. }
  64192. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  64193. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  64194. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  64195. };
  64196. Sound.prototype.detachFromMesh = function () {
  64197. if (this._connectedMesh && this._registerFunc) {
  64198. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64199. this._registerFunc = null;
  64200. this._connectedMesh = null;
  64201. }
  64202. };
  64203. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  64204. if (!node.getBoundingInfo) {
  64205. return;
  64206. }
  64207. var mesh = node;
  64208. var boundingInfo = mesh.getBoundingInfo();
  64209. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  64210. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  64211. this._updateDirection();
  64212. }
  64213. };
  64214. Sound.prototype.clone = function () {
  64215. var _this = this;
  64216. if (!this._streaming) {
  64217. var setBufferAndRun = function () {
  64218. if (_this._isReadyToPlay) {
  64219. clonedSound._audioBuffer = _this.getAudioBuffer();
  64220. clonedSound._isReadyToPlay = true;
  64221. if (clonedSound.autoplay) {
  64222. clonedSound.play();
  64223. }
  64224. }
  64225. else {
  64226. window.setTimeout(setBufferAndRun, 300);
  64227. }
  64228. };
  64229. var currentOptions = {
  64230. autoplay: this.autoplay, loop: this.loop,
  64231. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  64232. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  64233. refDistance: this.refDistance, distanceModel: this.distanceModel
  64234. };
  64235. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  64236. if (this.useCustomAttenuation) {
  64237. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  64238. }
  64239. clonedSound.setPosition(this._position);
  64240. clonedSound.setPlaybackRate(this._playbackRate);
  64241. setBufferAndRun();
  64242. return clonedSound;
  64243. }
  64244. // Can't clone a streaming sound
  64245. else {
  64246. return null;
  64247. }
  64248. };
  64249. Sound.prototype.getAudioBuffer = function () {
  64250. return this._audioBuffer;
  64251. };
  64252. Sound.prototype.serialize = function () {
  64253. var serializationObject = {
  64254. name: this.name,
  64255. url: this.name,
  64256. autoplay: this.autoplay,
  64257. loop: this.loop,
  64258. volume: this._volume,
  64259. spatialSound: this.spatialSound,
  64260. maxDistance: this.maxDistance,
  64261. rolloffFactor: this.rolloffFactor,
  64262. refDistance: this.refDistance,
  64263. distanceModel: this.distanceModel,
  64264. playbackRate: this._playbackRate,
  64265. panningModel: this._panningModel,
  64266. soundTrackId: this.soundTrackId
  64267. };
  64268. if (this.spatialSound) {
  64269. if (this._connectedMesh)
  64270. serializationObject.connectedMeshId = this._connectedMesh.id;
  64271. serializationObject.position = this._position.asArray();
  64272. serializationObject.refDistance = this.refDistance;
  64273. serializationObject.distanceModel = this.distanceModel;
  64274. serializationObject.isDirectional = this._isDirectional;
  64275. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  64276. serializationObject.coneInnerAngle = this._coneInnerAngle;
  64277. serializationObject.coneOuterAngle = this._coneOuterAngle;
  64278. serializationObject.coneOuterGain = this._coneOuterGain;
  64279. }
  64280. return serializationObject;
  64281. };
  64282. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  64283. var soundName = parsedSound.name;
  64284. var soundUrl;
  64285. if (parsedSound.url) {
  64286. soundUrl = rootUrl + parsedSound.url;
  64287. }
  64288. else {
  64289. soundUrl = rootUrl + soundName;
  64290. }
  64291. var options = {
  64292. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  64293. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  64294. rolloffFactor: parsedSound.rolloffFactor,
  64295. refDistance: parsedSound.refDistance,
  64296. distanceModel: parsedSound.distanceModel,
  64297. playbackRate: parsedSound.playbackRate
  64298. };
  64299. var newSound;
  64300. if (!sourceSound) {
  64301. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  64302. scene._addPendingData(newSound);
  64303. }
  64304. else {
  64305. var setBufferAndRun = function () {
  64306. if (sourceSound._isReadyToPlay) {
  64307. newSound._audioBuffer = sourceSound.getAudioBuffer();
  64308. newSound._isReadyToPlay = true;
  64309. if (newSound.autoplay) {
  64310. newSound.play();
  64311. }
  64312. }
  64313. else {
  64314. window.setTimeout(setBufferAndRun, 300);
  64315. }
  64316. };
  64317. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  64318. setBufferAndRun();
  64319. }
  64320. if (parsedSound.position) {
  64321. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  64322. newSound.setPosition(soundPosition);
  64323. }
  64324. if (parsedSound.isDirectional) {
  64325. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  64326. if (parsedSound.localDirectionToMesh) {
  64327. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  64328. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  64329. }
  64330. }
  64331. if (parsedSound.connectedMeshId) {
  64332. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  64333. if (connectedMesh) {
  64334. newSound.attachToMesh(connectedMesh);
  64335. }
  64336. }
  64337. return newSound;
  64338. };
  64339. return Sound;
  64340. }());
  64341. BABYLON.Sound = Sound;
  64342. })(BABYLON || (BABYLON = {}));
  64343. //# sourceMappingURL=babylon.sound.js.map
  64344. var BABYLON;
  64345. (function (BABYLON) {
  64346. var SoundTrack = /** @class */ (function () {
  64347. function SoundTrack(scene, options) {
  64348. this.id = -1;
  64349. this._isMainTrack = false;
  64350. this._isInitialized = false;
  64351. this._scene = scene;
  64352. this.soundCollection = new Array();
  64353. this._options = options;
  64354. if (!this._isMainTrack) {
  64355. this._scene.soundTracks.push(this);
  64356. this.id = this._scene.soundTracks.length - 1;
  64357. }
  64358. }
  64359. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  64360. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64361. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  64362. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  64363. if (this._options) {
  64364. if (this._options.volume) {
  64365. this._outputAudioNode.gain.value = this._options.volume;
  64366. }
  64367. if (this._options.mainTrack) {
  64368. this._isMainTrack = this._options.mainTrack;
  64369. }
  64370. }
  64371. this._isInitialized = true;
  64372. }
  64373. };
  64374. SoundTrack.prototype.dispose = function () {
  64375. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  64376. if (this._connectedAnalyser) {
  64377. this._connectedAnalyser.stopDebugCanvas();
  64378. }
  64379. while (this.soundCollection.length) {
  64380. this.soundCollection[0].dispose();
  64381. }
  64382. if (this._outputAudioNode) {
  64383. this._outputAudioNode.disconnect();
  64384. }
  64385. this._outputAudioNode = null;
  64386. }
  64387. };
  64388. SoundTrack.prototype.AddSound = function (sound) {
  64389. if (!this._isInitialized) {
  64390. this._initializeSoundTrackAudioGraph();
  64391. }
  64392. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64393. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  64394. }
  64395. if (sound.soundTrackId) {
  64396. if (sound.soundTrackId === -1) {
  64397. this._scene.mainSoundTrack.RemoveSound(sound);
  64398. }
  64399. else {
  64400. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  64401. }
  64402. }
  64403. this.soundCollection.push(sound);
  64404. sound.soundTrackId = this.id;
  64405. };
  64406. SoundTrack.prototype.RemoveSound = function (sound) {
  64407. var index = this.soundCollection.indexOf(sound);
  64408. if (index !== -1) {
  64409. this.soundCollection.splice(index, 1);
  64410. }
  64411. };
  64412. SoundTrack.prototype.setVolume = function (newVolume) {
  64413. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64414. this._outputAudioNode.gain.value = newVolume;
  64415. }
  64416. };
  64417. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  64418. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64419. for (var i = 0; i < this.soundCollection.length; i++) {
  64420. this.soundCollection[i].switchPanningModelToHRTF();
  64421. }
  64422. }
  64423. };
  64424. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  64425. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64426. for (var i = 0; i < this.soundCollection.length; i++) {
  64427. this.soundCollection[i].switchPanningModelToEqualPower();
  64428. }
  64429. }
  64430. };
  64431. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64432. if (this._connectedAnalyser) {
  64433. this._connectedAnalyser.stopDebugCanvas();
  64434. }
  64435. this._connectedAnalyser = analyser;
  64436. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64437. this._outputAudioNode.disconnect();
  64438. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64439. }
  64440. };
  64441. return SoundTrack;
  64442. }());
  64443. BABYLON.SoundTrack = SoundTrack;
  64444. })(BABYLON || (BABYLON = {}));
  64445. //# sourceMappingURL=babylon.soundtrack.js.map
  64446. var BABYLON;
  64447. (function (BABYLON) {
  64448. /**
  64449. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64450. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64451. */
  64452. var Analyser = /** @class */ (function () {
  64453. /**
  64454. * Creates a new analyser
  64455. * @param scene defines hosting scene
  64456. */
  64457. function Analyser(scene) {
  64458. /**
  64459. * Gets or sets the smoothing
  64460. * @ignorenaming
  64461. */
  64462. this.SMOOTHING = 0.75;
  64463. /**
  64464. * Gets or sets the FFT table size
  64465. * @ignorenaming
  64466. */
  64467. this.FFT_SIZE = 512;
  64468. /**
  64469. * Gets or sets the bar graph amplitude
  64470. * @ignorenaming
  64471. */
  64472. this.BARGRAPHAMPLITUDE = 256;
  64473. /**
  64474. * Gets or sets the position of the debug canvas
  64475. * @ignorenaming
  64476. */
  64477. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64478. /**
  64479. * Gets or sets the debug canvas size
  64480. * @ignorenaming
  64481. */
  64482. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64483. this._scene = scene;
  64484. this._audioEngine = BABYLON.Engine.audioEngine;
  64485. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64486. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64487. this._webAudioAnalyser.minDecibels = -140;
  64488. this._webAudioAnalyser.maxDecibels = 0;
  64489. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64490. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64491. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64492. }
  64493. }
  64494. /**
  64495. * Get the number of data values you will have to play with for the visualization
  64496. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64497. * @returns a number
  64498. */
  64499. Analyser.prototype.getFrequencyBinCount = function () {
  64500. if (this._audioEngine.canUseWebAudio) {
  64501. return this._webAudioAnalyser.frequencyBinCount;
  64502. }
  64503. else {
  64504. return 0;
  64505. }
  64506. };
  64507. /**
  64508. * Gets the current frequency data as a byte array
  64509. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64510. * @returns a Uint8Array
  64511. */
  64512. Analyser.prototype.getByteFrequencyData = function () {
  64513. if (this._audioEngine.canUseWebAudio) {
  64514. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64515. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64516. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  64517. }
  64518. return this._byteFreqs;
  64519. };
  64520. /**
  64521. * Gets the current waveform as a byte array
  64522. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  64523. * @returns a Uint8Array
  64524. */
  64525. Analyser.prototype.getByteTimeDomainData = function () {
  64526. if (this._audioEngine.canUseWebAudio) {
  64527. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64528. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64529. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  64530. }
  64531. return this._byteTime;
  64532. };
  64533. /**
  64534. * Gets the current frequency data as a float array
  64535. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64536. * @returns a Float32Array
  64537. */
  64538. Analyser.prototype.getFloatFrequencyData = function () {
  64539. if (this._audioEngine.canUseWebAudio) {
  64540. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64541. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64542. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  64543. }
  64544. return this._floatFreqs;
  64545. };
  64546. /**
  64547. * Renders the debug canvas
  64548. */
  64549. Analyser.prototype.drawDebugCanvas = function () {
  64550. var _this = this;
  64551. if (this._audioEngine.canUseWebAudio) {
  64552. if (!this._debugCanvas) {
  64553. this._debugCanvas = document.createElement("canvas");
  64554. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  64555. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  64556. this._debugCanvas.style.position = "absolute";
  64557. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  64558. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  64559. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  64560. document.body.appendChild(this._debugCanvas);
  64561. this._registerFunc = function () {
  64562. _this.drawDebugCanvas();
  64563. };
  64564. this._scene.registerBeforeRender(this._registerFunc);
  64565. }
  64566. if (this._registerFunc && this._debugCanvasContext) {
  64567. var workingArray = this.getByteFrequencyData();
  64568. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  64569. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  64570. // Draw the frequency domain chart.
  64571. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  64572. var value = workingArray[i];
  64573. var percent = value / this.BARGRAPHAMPLITUDE;
  64574. var height = this.DEBUGCANVASSIZE.height * percent;
  64575. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  64576. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  64577. var hue = i / this.getFrequencyBinCount() * 360;
  64578. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  64579. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  64580. }
  64581. }
  64582. }
  64583. };
  64584. /**
  64585. * Stops rendering the debug canvas and removes it
  64586. */
  64587. Analyser.prototype.stopDebugCanvas = function () {
  64588. if (this._debugCanvas) {
  64589. if (this._registerFunc) {
  64590. this._scene.unregisterBeforeRender(this._registerFunc);
  64591. this._registerFunc = null;
  64592. }
  64593. document.body.removeChild(this._debugCanvas);
  64594. this._debugCanvas = null;
  64595. this._debugCanvasContext = null;
  64596. }
  64597. };
  64598. /**
  64599. * Connects two audio nodes
  64600. * @param inputAudioNode defines first node to connect
  64601. * @param outputAudioNode defines second node to connect
  64602. */
  64603. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  64604. if (this._audioEngine.canUseWebAudio) {
  64605. inputAudioNode.connect(this._webAudioAnalyser);
  64606. this._webAudioAnalyser.connect(outputAudioNode);
  64607. }
  64608. };
  64609. /**
  64610. * Releases all associated resources
  64611. */
  64612. Analyser.prototype.dispose = function () {
  64613. if (this._audioEngine.canUseWebAudio) {
  64614. this._webAudioAnalyser.disconnect();
  64615. }
  64616. };
  64617. return Analyser;
  64618. }());
  64619. BABYLON.Analyser = Analyser;
  64620. })(BABYLON || (BABYLON = {}));
  64621. //# sourceMappingURL=babylon.analyser.js.map
  64622. var BABYLON;
  64623. (function (BABYLON) {
  64624. var CubeTexture = /** @class */ (function (_super) {
  64625. __extends(CubeTexture, _super);
  64626. /**
  64627. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  64628. * as prefiltered data.
  64629. * @param rootUrl defines the url of the texture or the root name of the six images
  64630. * @param scene defines the scene the texture is attached to
  64631. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  64632. * @param noMipmap defines if mipmaps should be created or not
  64633. * @param files defines the six files to load for the different faces
  64634. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  64635. * @param onError defines a callback triggered in case of error during load
  64636. * @param format defines the internal format to use for the texture once loaded
  64637. * @param prefiltered defines whether or not the texture is created from prefiltered data
  64638. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  64639. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64640. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64641. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64642. * @return the cube texture
  64643. */
  64644. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  64645. if (extensions === void 0) { extensions = null; }
  64646. if (noMipmap === void 0) { noMipmap = false; }
  64647. if (files === void 0) { files = null; }
  64648. if (onLoad === void 0) { onLoad = null; }
  64649. if (onError === void 0) { onError = null; }
  64650. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64651. if (prefiltered === void 0) { prefiltered = false; }
  64652. if (forcedExtension === void 0) { forcedExtension = null; }
  64653. if (createPolynomials === void 0) { createPolynomials = false; }
  64654. if (lodScale === void 0) { lodScale = 0.8; }
  64655. if (lodOffset === void 0) { lodOffset = 0; }
  64656. var _this = _super.call(this, scene) || this;
  64657. /**
  64658. * Gets or sets the center of the bounding box associated with the cube texture
  64659. * It must define where the camera used to render the texture was set
  64660. */
  64661. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64662. _this._rotationY = 0;
  64663. /** @hidden */
  64664. _this._prefiltered = false;
  64665. _this.name = rootUrl;
  64666. _this.url = rootUrl;
  64667. _this._noMipmap = noMipmap;
  64668. _this.hasAlpha = false;
  64669. _this._format = format;
  64670. _this.isCube = true;
  64671. _this._textureMatrix = BABYLON.Matrix.Identity();
  64672. _this._createPolynomials = createPolynomials;
  64673. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64674. if (!rootUrl && !files) {
  64675. return _this;
  64676. }
  64677. var lastDot = rootUrl.lastIndexOf(".");
  64678. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  64679. var isDDS = (extension === ".dds");
  64680. var isEnv = (extension === ".env");
  64681. if (isEnv) {
  64682. _this.gammaSpace = false;
  64683. _this._prefiltered = false;
  64684. }
  64685. else {
  64686. _this._prefiltered = prefiltered;
  64687. if (prefiltered) {
  64688. _this.gammaSpace = false;
  64689. }
  64690. }
  64691. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  64692. if (!files) {
  64693. if (!isEnv && !isDDS && !extensions) {
  64694. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  64695. }
  64696. files = [];
  64697. if (extensions) {
  64698. for (var index = 0; index < extensions.length; index++) {
  64699. files.push(rootUrl + extensions[index]);
  64700. }
  64701. }
  64702. }
  64703. _this._files = files;
  64704. if (!_this._texture) {
  64705. if (!scene.useDelayedTextureLoading) {
  64706. if (prefiltered) {
  64707. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  64708. }
  64709. else {
  64710. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  64711. }
  64712. }
  64713. else {
  64714. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64715. }
  64716. }
  64717. else if (onLoad) {
  64718. if (_this._texture.isReady) {
  64719. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  64720. }
  64721. else {
  64722. _this._texture.onLoadedObservable.add(onLoad);
  64723. }
  64724. }
  64725. return _this;
  64726. }
  64727. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  64728. get: function () {
  64729. return this._boundingBoxSize;
  64730. },
  64731. /**
  64732. * Gets or sets the size of the bounding box associated with the cube texture
  64733. * When defined, the cubemap will switch to local mode
  64734. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64735. * @example https://www.babylonjs-playground.com/#RNASML
  64736. */
  64737. set: function (value) {
  64738. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64739. return;
  64740. }
  64741. this._boundingBoxSize = value;
  64742. var scene = this.getScene();
  64743. if (scene) {
  64744. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64745. }
  64746. },
  64747. enumerable: true,
  64748. configurable: true
  64749. });
  64750. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  64751. /**
  64752. * Gets texture matrix rotation angle around Y axis radians.
  64753. */
  64754. get: function () {
  64755. return this._rotationY;
  64756. },
  64757. /**
  64758. * Sets texture matrix rotation angle around Y axis in radians.
  64759. */
  64760. set: function (value) {
  64761. this._rotationY = value;
  64762. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  64763. },
  64764. enumerable: true,
  64765. configurable: true
  64766. });
  64767. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  64768. var rootUrlKey = "";
  64769. files.forEach(function (url) { return rootUrlKey += url; });
  64770. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  64771. };
  64772. /**
  64773. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  64774. * @param url defines the url of the prefiltered texture
  64775. * @param scene defines the scene the texture is attached to
  64776. * @param forcedExtension defines the extension of the file if different from the url
  64777. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64778. * @return the prefiltered texture
  64779. */
  64780. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  64781. if (forcedExtension === void 0) { forcedExtension = null; }
  64782. if (createPolynomials === void 0) { createPolynomials = true; }
  64783. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  64784. };
  64785. // Methods
  64786. CubeTexture.prototype.delayLoad = function () {
  64787. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64788. return;
  64789. }
  64790. var scene = this.getScene();
  64791. if (!scene) {
  64792. return;
  64793. }
  64794. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64795. this._texture = this._getFromCache(this.url, this._noMipmap);
  64796. if (!this._texture) {
  64797. if (this._prefiltered) {
  64798. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  64799. }
  64800. else {
  64801. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  64802. }
  64803. }
  64804. };
  64805. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  64806. return this._textureMatrix;
  64807. };
  64808. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64809. this._textureMatrix = value;
  64810. };
  64811. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64812. var texture = BABYLON.SerializationHelper.Parse(function () {
  64813. var prefiltered = false;
  64814. if (parsedTexture.prefiltered) {
  64815. prefiltered = parsedTexture.prefiltered;
  64816. }
  64817. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  64818. }, parsedTexture, scene);
  64819. // Local Cubemaps
  64820. if (parsedTexture.boundingBoxPosition) {
  64821. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  64822. }
  64823. if (parsedTexture.boundingBoxSize) {
  64824. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  64825. }
  64826. // Animations
  64827. if (parsedTexture.animations) {
  64828. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  64829. var parsedAnimation = parsedTexture.animations[animationIndex];
  64830. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  64831. }
  64832. }
  64833. return texture;
  64834. };
  64835. CubeTexture.prototype.clone = function () {
  64836. var _this = this;
  64837. return BABYLON.SerializationHelper.Clone(function () {
  64838. var scene = _this.getScene();
  64839. if (!scene) {
  64840. return _this;
  64841. }
  64842. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  64843. }, this);
  64844. };
  64845. __decorate([
  64846. BABYLON.serialize("rotationY")
  64847. ], CubeTexture.prototype, "_rotationY", void 0);
  64848. return CubeTexture;
  64849. }(BABYLON.BaseTexture));
  64850. BABYLON.CubeTexture = CubeTexture;
  64851. })(BABYLON || (BABYLON = {}));
  64852. //# sourceMappingURL=babylon.cubeTexture.js.map
  64853. var BABYLON;
  64854. (function (BABYLON) {
  64855. /**
  64856. * Raw cube texture where the raw buffers are passed in
  64857. */
  64858. var RawCubeTexture = /** @class */ (function (_super) {
  64859. __extends(RawCubeTexture, _super);
  64860. /**
  64861. * Creates a cube texture where the raw buffers are passed in.
  64862. * @param scene defines the scene the texture is attached to
  64863. * @param data defines the array of data to use to create each face
  64864. * @param size defines the size of the textures
  64865. * @param format defines the format of the data
  64866. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  64867. * @param generateMipMaps defines if the engine should generate the mip levels
  64868. * @param invertY defines if data must be stored with Y axis inverted
  64869. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  64870. * @param compression defines the compression used (null by default)
  64871. */
  64872. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  64873. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64874. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64875. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64876. if (invertY === void 0) { invertY = false; }
  64877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64878. if (compression === void 0) { compression = null; }
  64879. var _this = _super.call(this, "", scene) || this;
  64880. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  64881. return _this;
  64882. }
  64883. /**
  64884. * Updates the raw cube texture.
  64885. * @param data defines the data to store
  64886. * @param format defines the data format
  64887. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  64888. * @param invertY defines if data must be stored with Y axis inverted
  64889. * @param compression defines the compression used (null by default)
  64890. * @param level defines which level of the texture to update
  64891. */
  64892. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  64893. if (compression === void 0) { compression = null; }
  64894. if (level === void 0) { level = 0; }
  64895. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  64896. };
  64897. /**
  64898. * Updates a raw cube texture with RGBD encoded data.
  64899. * @param data defines the array of data [mipmap][face] to use to create each face
  64900. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  64901. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64902. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64903. * @returns a promsie that resolves when the operation is complete
  64904. */
  64905. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  64906. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  64907. if (lodScale === void 0) { lodScale = 0.8; }
  64908. if (lodOffset === void 0) { lodOffset = 0; }
  64909. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  64910. };
  64911. /**
  64912. * Clones the raw cube texture.
  64913. * @return a new cube texture
  64914. */
  64915. RawCubeTexture.prototype.clone = function () {
  64916. var _this = this;
  64917. return BABYLON.SerializationHelper.Clone(function () {
  64918. var scene = _this.getScene();
  64919. var internalTexture = _this._texture;
  64920. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  64921. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  64922. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  64923. }
  64924. return texture;
  64925. }, this);
  64926. };
  64927. /** @hidden */
  64928. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  64929. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  64930. internalTexture._bufferViewArrayArray = data;
  64931. internalTexture._lodGenerationScale = lodScale;
  64932. internalTexture._lodGenerationOffset = lodOffset;
  64933. internalTexture._sphericalPolynomial = sphericalPolynomial;
  64934. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  64935. internalTexture.isReady = true;
  64936. });
  64937. };
  64938. return RawCubeTexture;
  64939. }(BABYLON.CubeTexture));
  64940. BABYLON.RawCubeTexture = RawCubeTexture;
  64941. })(BABYLON || (BABYLON = {}));
  64942. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  64943. var BABYLON;
  64944. (function (BABYLON) {
  64945. var RenderTargetTexture = /** @class */ (function (_super) {
  64946. __extends(RenderTargetTexture, _super);
  64947. /**
  64948. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  64949. * or used a shadow, depth texture...
  64950. * @param name The friendly name of the texture
  64951. * @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)
  64952. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  64953. * @param generateMipMaps True if mip maps need to be generated after render.
  64954. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  64955. * @param type The type of the buffer in the RTT (int, half float, float...)
  64956. * @param isCube True if a cube texture needs to be created
  64957. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  64958. * @param generateDepthBuffer True to generate a depth buffer
  64959. * @param generateStencilBuffer True to generate a stencil buffer
  64960. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  64961. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  64962. */
  64963. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  64964. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  64965. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64966. if (isCube === void 0) { isCube = false; }
  64967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64968. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64969. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  64970. if (isMulti === void 0) { isMulti = false; }
  64971. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64972. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64973. _this.isCube = isCube;
  64974. /**
  64975. * Use this list to define the list of mesh you want to render.
  64976. */
  64977. _this.renderList = new Array();
  64978. _this.renderParticles = true;
  64979. _this.renderSprites = false;
  64980. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  64981. _this.ignoreCameraViewport = false;
  64982. // Events
  64983. /**
  64984. * An event triggered when the texture is unbind.
  64985. */
  64986. _this.onBeforeBindObservable = new BABYLON.Observable();
  64987. /**
  64988. * An event triggered when the texture is unbind.
  64989. */
  64990. _this.onAfterUnbindObservable = new BABYLON.Observable();
  64991. /**
  64992. * An event triggered before rendering the texture
  64993. */
  64994. _this.onBeforeRenderObservable = new BABYLON.Observable();
  64995. /**
  64996. * An event triggered after rendering the texture
  64997. */
  64998. _this.onAfterRenderObservable = new BABYLON.Observable();
  64999. /**
  65000. * An event triggered after the texture clear
  65001. */
  65002. _this.onClearObservable = new BABYLON.Observable();
  65003. _this._currentRefreshId = -1;
  65004. _this._refreshRate = 1;
  65005. _this._samples = 1;
  65006. /**
  65007. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  65008. * It must define where the camera used to render the texture is set
  65009. */
  65010. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65011. scene = _this.getScene();
  65012. if (!scene) {
  65013. return _this;
  65014. }
  65015. _this._engine = scene.getEngine();
  65016. _this.name = name;
  65017. _this.isRenderTarget = true;
  65018. _this._initialSizeParameter = size;
  65019. _this._processSizeParameter(size);
  65020. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  65021. });
  65022. _this._generateMipMaps = generateMipMaps ? true : false;
  65023. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  65024. // Rendering groups
  65025. _this._renderingManager = new BABYLON.RenderingManager(scene);
  65026. _this._renderingManager._useSceneAutoClearSetup = true;
  65027. if (isMulti) {
  65028. return _this;
  65029. }
  65030. _this._renderTargetOptions = {
  65031. generateMipMaps: generateMipMaps,
  65032. type: type,
  65033. format: format,
  65034. samplingMode: samplingMode,
  65035. generateDepthBuffer: generateDepthBuffer,
  65036. generateStencilBuffer: generateStencilBuffer
  65037. };
  65038. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  65039. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65040. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65041. }
  65042. if (isCube) {
  65043. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  65044. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  65045. _this._textureMatrix = BABYLON.Matrix.Identity();
  65046. }
  65047. else {
  65048. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  65049. }
  65050. return _this;
  65051. }
  65052. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  65053. get: function () {
  65054. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  65055. },
  65056. enumerable: true,
  65057. configurable: true
  65058. });
  65059. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  65060. get: function () {
  65061. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  65062. },
  65063. enumerable: true,
  65064. configurable: true
  65065. });
  65066. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  65067. get: function () {
  65068. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  65069. },
  65070. enumerable: true,
  65071. configurable: true
  65072. });
  65073. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  65074. set: function (callback) {
  65075. if (this._onAfterUnbindObserver) {
  65076. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  65077. }
  65078. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  65079. },
  65080. enumerable: true,
  65081. configurable: true
  65082. });
  65083. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  65084. set: function (callback) {
  65085. if (this._onBeforeRenderObserver) {
  65086. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65087. }
  65088. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65089. },
  65090. enumerable: true,
  65091. configurable: true
  65092. });
  65093. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  65094. set: function (callback) {
  65095. if (this._onAfterRenderObserver) {
  65096. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65097. }
  65098. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65099. },
  65100. enumerable: true,
  65101. configurable: true
  65102. });
  65103. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  65104. set: function (callback) {
  65105. if (this._onClearObserver) {
  65106. this.onClearObservable.remove(this._onClearObserver);
  65107. }
  65108. this._onClearObserver = this.onClearObservable.add(callback);
  65109. },
  65110. enumerable: true,
  65111. configurable: true
  65112. });
  65113. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  65114. get: function () {
  65115. return this._renderTargetOptions;
  65116. },
  65117. enumerable: true,
  65118. configurable: true
  65119. });
  65120. RenderTargetTexture.prototype._onRatioRescale = function () {
  65121. if (this._sizeRatio) {
  65122. this.resize(this._initialSizeParameter);
  65123. }
  65124. };
  65125. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  65126. get: function () {
  65127. return this._boundingBoxSize;
  65128. },
  65129. /**
  65130. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  65131. * When defined, the cubemap will switch to local mode
  65132. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65133. * @example https://www.babylonjs-playground.com/#RNASML
  65134. */
  65135. set: function (value) {
  65136. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65137. return;
  65138. }
  65139. this._boundingBoxSize = value;
  65140. var scene = this.getScene();
  65141. if (scene) {
  65142. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65143. }
  65144. },
  65145. enumerable: true,
  65146. configurable: true
  65147. });
  65148. /**
  65149. * Creates a depth stencil texture.
  65150. * This is only available in WebGL 2 or with the depth texture extension available.
  65151. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  65152. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  65153. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  65154. */
  65155. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  65156. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  65157. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  65158. if (generateStencil === void 0) { generateStencil = false; }
  65159. if (!this.getScene()) {
  65160. return;
  65161. }
  65162. var engine = this.getScene().getEngine();
  65163. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  65164. bilinearFiltering: bilinearFiltering,
  65165. comparisonFunction: comparisonFunction,
  65166. generateStencil: generateStencil,
  65167. isCube: this.isCube
  65168. });
  65169. engine.setFrameBufferDepthStencilTexture(this);
  65170. };
  65171. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  65172. if (size.ratio) {
  65173. this._sizeRatio = size.ratio;
  65174. this._size = {
  65175. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  65176. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  65177. };
  65178. }
  65179. else {
  65180. this._size = size;
  65181. }
  65182. };
  65183. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  65184. get: function () {
  65185. return this._samples;
  65186. },
  65187. set: function (value) {
  65188. if (this._samples === value) {
  65189. return;
  65190. }
  65191. var scene = this.getScene();
  65192. if (!scene) {
  65193. return;
  65194. }
  65195. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  65196. },
  65197. enumerable: true,
  65198. configurable: true
  65199. });
  65200. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  65201. this._currentRefreshId = -1;
  65202. };
  65203. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  65204. get: function () {
  65205. return this._refreshRate;
  65206. },
  65207. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65208. set: function (value) {
  65209. this._refreshRate = value;
  65210. this.resetRefreshCounter();
  65211. },
  65212. enumerable: true,
  65213. configurable: true
  65214. });
  65215. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  65216. if (!this._postProcessManager) {
  65217. var scene = this.getScene();
  65218. if (!scene) {
  65219. return;
  65220. }
  65221. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  65222. this._postProcesses = new Array();
  65223. }
  65224. this._postProcesses.push(postProcess);
  65225. this._postProcesses[0].autoClear = false;
  65226. };
  65227. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  65228. if (!this._postProcesses) {
  65229. return;
  65230. }
  65231. if (dispose) {
  65232. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  65233. var postProcess = _a[_i];
  65234. postProcess.dispose();
  65235. }
  65236. }
  65237. this._postProcesses = [];
  65238. };
  65239. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  65240. if (!this._postProcesses) {
  65241. return;
  65242. }
  65243. var index = this._postProcesses.indexOf(postProcess);
  65244. if (index === -1) {
  65245. return;
  65246. }
  65247. this._postProcesses.splice(index, 1);
  65248. if (this._postProcesses.length > 0) {
  65249. this._postProcesses[0].autoClear = false;
  65250. }
  65251. };
  65252. RenderTargetTexture.prototype._shouldRender = function () {
  65253. if (this._currentRefreshId === -1) { // At least render once
  65254. this._currentRefreshId = 1;
  65255. return true;
  65256. }
  65257. if (this.refreshRate === this._currentRefreshId) {
  65258. this._currentRefreshId = 1;
  65259. return true;
  65260. }
  65261. this._currentRefreshId++;
  65262. return false;
  65263. };
  65264. RenderTargetTexture.prototype.getRenderSize = function () {
  65265. if (this._size.width) {
  65266. return this._size.width;
  65267. }
  65268. return this._size;
  65269. };
  65270. RenderTargetTexture.prototype.getRenderWidth = function () {
  65271. if (this._size.width) {
  65272. return this._size.width;
  65273. }
  65274. return this._size;
  65275. };
  65276. RenderTargetTexture.prototype.getRenderHeight = function () {
  65277. if (this._size.width) {
  65278. return this._size.height;
  65279. }
  65280. return this._size;
  65281. };
  65282. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  65283. get: function () {
  65284. return true;
  65285. },
  65286. enumerable: true,
  65287. configurable: true
  65288. });
  65289. RenderTargetTexture.prototype.scale = function (ratio) {
  65290. var newSize = this.getRenderSize() * ratio;
  65291. this.resize(newSize);
  65292. };
  65293. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  65294. if (this.isCube) {
  65295. return this._textureMatrix;
  65296. }
  65297. return _super.prototype.getReflectionTextureMatrix.call(this);
  65298. };
  65299. RenderTargetTexture.prototype.resize = function (size) {
  65300. this.releaseInternalTexture();
  65301. var scene = this.getScene();
  65302. if (!scene) {
  65303. return;
  65304. }
  65305. this._processSizeParameter(size);
  65306. if (this.isCube) {
  65307. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  65308. }
  65309. else {
  65310. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  65311. }
  65312. };
  65313. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  65314. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  65315. if (dumpForDebug === void 0) { dumpForDebug = false; }
  65316. var scene = this.getScene();
  65317. if (!scene) {
  65318. return;
  65319. }
  65320. var engine = scene.getEngine();
  65321. if (this.useCameraPostProcesses !== undefined) {
  65322. useCameraPostProcess = this.useCameraPostProcesses;
  65323. }
  65324. if (this._waitingRenderList) {
  65325. this.renderList = [];
  65326. for (var index = 0; index < this._waitingRenderList.length; index++) {
  65327. var id = this._waitingRenderList[index];
  65328. var mesh_1 = scene.getMeshByID(id);
  65329. if (mesh_1) {
  65330. this.renderList.push(mesh_1);
  65331. }
  65332. }
  65333. delete this._waitingRenderList;
  65334. }
  65335. // Is predicate defined?
  65336. if (this.renderListPredicate) {
  65337. if (this.renderList) {
  65338. this.renderList.splice(0); // Clear previous renderList
  65339. }
  65340. else {
  65341. this.renderList = [];
  65342. }
  65343. var scene = this.getScene();
  65344. if (!scene) {
  65345. return;
  65346. }
  65347. var sceneMeshes = scene.meshes;
  65348. for (var index = 0; index < sceneMeshes.length; index++) {
  65349. var mesh = sceneMeshes[index];
  65350. if (this.renderListPredicate(mesh)) {
  65351. this.renderList.push(mesh);
  65352. }
  65353. }
  65354. }
  65355. this.onBeforeBindObservable.notifyObservers(this);
  65356. // Set custom projection.
  65357. // Needs to be before binding to prevent changing the aspect ratio.
  65358. var camera;
  65359. if (this.activeCamera) {
  65360. camera = this.activeCamera;
  65361. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65362. if (this.activeCamera !== scene.activeCamera) {
  65363. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  65364. }
  65365. }
  65366. else {
  65367. camera = scene.activeCamera;
  65368. if (camera) {
  65369. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65370. }
  65371. }
  65372. // Prepare renderingManager
  65373. this._renderingManager.reset();
  65374. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  65375. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  65376. var sceneRenderId = scene.getRenderId();
  65377. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  65378. var mesh = currentRenderList[meshIndex];
  65379. if (mesh) {
  65380. if (!mesh.isReady(this.refreshRate === 0)) {
  65381. this.resetRefreshCounter();
  65382. continue;
  65383. }
  65384. mesh._preActivateForIntermediateRendering(sceneRenderId);
  65385. var isMasked = void 0;
  65386. if (!this.renderList && camera) {
  65387. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  65388. }
  65389. else {
  65390. isMasked = false;
  65391. }
  65392. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  65393. mesh._activate(sceneRenderId);
  65394. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  65395. var subMesh = mesh.subMeshes[subIndex];
  65396. scene._activeIndices.addCount(subMesh.indexCount, false);
  65397. this._renderingManager.dispatch(subMesh, mesh);
  65398. }
  65399. }
  65400. }
  65401. }
  65402. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  65403. var particleSystem = scene.particleSystems[particleIndex];
  65404. var emitter = particleSystem.emitter;
  65405. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  65406. continue;
  65407. }
  65408. if (currentRenderList.indexOf(emitter) >= 0) {
  65409. this._renderingManager.dispatchParticles(particleSystem);
  65410. }
  65411. }
  65412. if (this.isCube) {
  65413. for (var face = 0; face < 6; face++) {
  65414. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65415. scene.incrementRenderId();
  65416. scene.resetCachedMaterial();
  65417. }
  65418. }
  65419. else {
  65420. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65421. }
  65422. this.onAfterUnbindObservable.notifyObservers(this);
  65423. if (scene.activeCamera) {
  65424. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  65425. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  65426. }
  65427. engine.setViewport(scene.activeCamera.viewport);
  65428. }
  65429. scene.resetCachedMaterial();
  65430. };
  65431. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  65432. var minimum = 128;
  65433. var x = renderDimension * scale;
  65434. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  65435. // Ensure we don't exceed the render dimension (while staying POT)
  65436. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  65437. };
  65438. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65439. var _this = this;
  65440. if (!this._texture) {
  65441. return;
  65442. }
  65443. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  65444. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65445. });
  65446. };
  65447. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  65448. var scene = this.getScene();
  65449. if (!scene) {
  65450. return;
  65451. }
  65452. var engine = scene.getEngine();
  65453. if (!this._texture) {
  65454. return;
  65455. }
  65456. // Bind
  65457. if (this._postProcessManager) {
  65458. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  65459. }
  65460. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  65461. if (this._texture) {
  65462. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  65463. }
  65464. }
  65465. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  65466. // Clear
  65467. if (this.onClearObservable.hasObservers()) {
  65468. this.onClearObservable.notifyObservers(engine);
  65469. }
  65470. else {
  65471. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  65472. }
  65473. if (!this._doNotChangeAspectRatio) {
  65474. scene.updateTransformMatrix(true);
  65475. }
  65476. // Render
  65477. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  65478. if (this._postProcessManager) {
  65479. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  65480. }
  65481. else if (useCameraPostProcess) {
  65482. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  65483. }
  65484. if (!this._doNotChangeAspectRatio) {
  65485. scene.updateTransformMatrix(true);
  65486. }
  65487. // Dump ?
  65488. if (dumpForDebug) {
  65489. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  65490. }
  65491. // Unbind
  65492. if (!this.isCube || faceIndex === 5) {
  65493. if (this.isCube) {
  65494. if (faceIndex === 5) {
  65495. engine.generateMipMapsForCubemap(this._texture);
  65496. }
  65497. }
  65498. this.unbindFrameBuffer(engine, faceIndex);
  65499. }
  65500. else {
  65501. this.onAfterRenderObservable.notifyObservers(faceIndex);
  65502. }
  65503. };
  65504. /**
  65505. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  65506. * This allowed control for front to back rendering or reversly depending of the special needs.
  65507. *
  65508. * @param renderingGroupId The rendering group id corresponding to its index
  65509. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  65510. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  65511. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  65512. */
  65513. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  65514. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  65515. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  65516. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  65517. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  65518. };
  65519. /**
  65520. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  65521. *
  65522. * @param renderingGroupId The rendering group id corresponding to its index
  65523. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  65524. */
  65525. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  65526. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  65527. this._renderingManager._useSceneAutoClearSetup = false;
  65528. };
  65529. RenderTargetTexture.prototype.clone = function () {
  65530. var textureSize = this.getSize();
  65531. 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);
  65532. // Base texture
  65533. newTexture.hasAlpha = this.hasAlpha;
  65534. newTexture.level = this.level;
  65535. // RenderTarget Texture
  65536. newTexture.coordinatesMode = this.coordinatesMode;
  65537. if (this.renderList) {
  65538. newTexture.renderList = this.renderList.slice(0);
  65539. }
  65540. return newTexture;
  65541. };
  65542. RenderTargetTexture.prototype.serialize = function () {
  65543. if (!this.name) {
  65544. return null;
  65545. }
  65546. var serializationObject = _super.prototype.serialize.call(this);
  65547. serializationObject.renderTargetSize = this.getRenderSize();
  65548. serializationObject.renderList = [];
  65549. if (this.renderList) {
  65550. for (var index = 0; index < this.renderList.length; index++) {
  65551. serializationObject.renderList.push(this.renderList[index].id);
  65552. }
  65553. }
  65554. return serializationObject;
  65555. };
  65556. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  65557. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  65558. var objBuffer = this.getInternalTexture();
  65559. var scene = this.getScene();
  65560. if (objBuffer && scene) {
  65561. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  65562. }
  65563. };
  65564. RenderTargetTexture.prototype.dispose = function () {
  65565. if (this._postProcessManager) {
  65566. this._postProcessManager.dispose();
  65567. this._postProcessManager = null;
  65568. }
  65569. this.clearPostProcesses(true);
  65570. if (this._resizeObserver) {
  65571. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  65572. this._resizeObserver = null;
  65573. }
  65574. this.renderList = null;
  65575. // Remove from custom render targets
  65576. var scene = this.getScene();
  65577. if (!scene) {
  65578. return;
  65579. }
  65580. var index = scene.customRenderTargets.indexOf(this);
  65581. if (index >= 0) {
  65582. scene.customRenderTargets.splice(index, 1);
  65583. }
  65584. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  65585. var camera = _a[_i];
  65586. index = camera.customRenderTargets.indexOf(this);
  65587. if (index >= 0) {
  65588. camera.customRenderTargets.splice(index, 1);
  65589. }
  65590. }
  65591. _super.prototype.dispose.call(this);
  65592. };
  65593. RenderTargetTexture.prototype._rebuild = function () {
  65594. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65595. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65596. }
  65597. if (this._postProcessManager) {
  65598. this._postProcessManager._rebuild();
  65599. }
  65600. };
  65601. /**
  65602. * Clear the info related to rendering groups preventing retention point in material dispose.
  65603. */
  65604. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  65605. if (this._renderingManager) {
  65606. this._renderingManager.freeRenderingGroups();
  65607. }
  65608. };
  65609. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  65610. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  65611. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  65612. return RenderTargetTexture;
  65613. }(BABYLON.Texture));
  65614. BABYLON.RenderTargetTexture = RenderTargetTexture;
  65615. })(BABYLON || (BABYLON = {}));
  65616. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  65617. var BABYLON;
  65618. (function (BABYLON) {
  65619. ;
  65620. var MultiRenderTarget = /** @class */ (function (_super) {
  65621. __extends(MultiRenderTarget, _super);
  65622. function MultiRenderTarget(name, size, count, scene, options) {
  65623. var _this = this;
  65624. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  65625. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  65626. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  65627. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  65628. _this._engine = scene.getEngine();
  65629. if (!_this.isSupported) {
  65630. _this.dispose();
  65631. return;
  65632. }
  65633. var types = [];
  65634. var samplingModes = [];
  65635. for (var i = 0; i < count; i++) {
  65636. if (options && options.types && options.types[i] !== undefined) {
  65637. types.push(options.types[i]);
  65638. }
  65639. else {
  65640. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65641. }
  65642. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  65643. samplingModes.push(options.samplingModes[i]);
  65644. }
  65645. else {
  65646. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65647. }
  65648. }
  65649. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  65650. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  65651. _this._size = size;
  65652. _this._multiRenderTargetOptions = {
  65653. samplingModes: samplingModes,
  65654. generateMipMaps: generateMipMaps,
  65655. generateDepthBuffer: generateDepthBuffer,
  65656. generateStencilBuffer: generateStencilBuffer,
  65657. generateDepthTexture: generateDepthTexture,
  65658. types: types,
  65659. textureCount: count
  65660. };
  65661. _this._createInternalTextures();
  65662. _this._createTextures();
  65663. return _this;
  65664. }
  65665. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  65666. get: function () {
  65667. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  65668. },
  65669. enumerable: true,
  65670. configurable: true
  65671. });
  65672. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  65673. get: function () {
  65674. return this._textures;
  65675. },
  65676. enumerable: true,
  65677. configurable: true
  65678. });
  65679. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  65680. get: function () {
  65681. return this._textures[this._textures.length - 1];
  65682. },
  65683. enumerable: true,
  65684. configurable: true
  65685. });
  65686. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  65687. set: function (wrap) {
  65688. if (this._textures) {
  65689. for (var i = 0; i < this._textures.length; i++) {
  65690. this._textures[i].wrapU = wrap;
  65691. }
  65692. }
  65693. },
  65694. enumerable: true,
  65695. configurable: true
  65696. });
  65697. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  65698. set: function (wrap) {
  65699. if (this._textures) {
  65700. for (var i = 0; i < this._textures.length; i++) {
  65701. this._textures[i].wrapV = wrap;
  65702. }
  65703. }
  65704. },
  65705. enumerable: true,
  65706. configurable: true
  65707. });
  65708. MultiRenderTarget.prototype._rebuild = function () {
  65709. this.releaseInternalTextures();
  65710. this._createInternalTextures();
  65711. for (var i = 0; i < this._internalTextures.length; i++) {
  65712. var texture = this._textures[i];
  65713. texture._texture = this._internalTextures[i];
  65714. }
  65715. // Keeps references to frame buffer and stencil/depth buffer
  65716. this._texture = this._internalTextures[0];
  65717. };
  65718. MultiRenderTarget.prototype._createInternalTextures = function () {
  65719. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  65720. };
  65721. MultiRenderTarget.prototype._createTextures = function () {
  65722. this._textures = [];
  65723. for (var i = 0; i < this._internalTextures.length; i++) {
  65724. var texture = new BABYLON.Texture(null, this.getScene());
  65725. texture._texture = this._internalTextures[i];
  65726. this._textures.push(texture);
  65727. }
  65728. // Keeps references to frame buffer and stencil/depth buffer
  65729. this._texture = this._internalTextures[0];
  65730. };
  65731. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  65732. get: function () {
  65733. return this._samples;
  65734. },
  65735. set: function (value) {
  65736. if (this._samples === value) {
  65737. return;
  65738. }
  65739. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  65740. },
  65741. enumerable: true,
  65742. configurable: true
  65743. });
  65744. MultiRenderTarget.prototype.resize = function (size) {
  65745. this.releaseInternalTextures();
  65746. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  65747. this._createInternalTextures();
  65748. };
  65749. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65750. var _this = this;
  65751. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  65752. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65753. });
  65754. };
  65755. MultiRenderTarget.prototype.dispose = function () {
  65756. this.releaseInternalTextures();
  65757. _super.prototype.dispose.call(this);
  65758. };
  65759. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  65760. if (!this._internalTextures) {
  65761. return;
  65762. }
  65763. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  65764. if (this._internalTextures[i] !== undefined) {
  65765. this._internalTextures[i].dispose();
  65766. this._internalTextures.splice(i, 1);
  65767. }
  65768. }
  65769. };
  65770. return MultiRenderTarget;
  65771. }(BABYLON.RenderTargetTexture));
  65772. BABYLON.MultiRenderTarget = MultiRenderTarget;
  65773. })(BABYLON || (BABYLON = {}));
  65774. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  65775. var BABYLON;
  65776. (function (BABYLON) {
  65777. var MirrorTexture = /** @class */ (function (_super) {
  65778. __extends(MirrorTexture, _super);
  65779. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  65780. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65782. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65783. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  65784. _this.scene = scene;
  65785. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  65786. _this._transformMatrix = BABYLON.Matrix.Zero();
  65787. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  65788. _this._adaptiveBlurKernel = 0;
  65789. _this._blurKernelX = 0;
  65790. _this._blurKernelY = 0;
  65791. _this._blurRatio = 1.0;
  65792. _this.ignoreCameraViewport = true;
  65793. _this._updateGammaSpace();
  65794. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  65795. _this._updateGammaSpace;
  65796. });
  65797. _this.onBeforeRenderObservable.add(function () {
  65798. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  65799. _this._savedViewMatrix = scene.getViewMatrix();
  65800. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  65801. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  65802. scene.clipPlane = _this.mirrorPlane;
  65803. scene.getEngine().cullBackFaces = false;
  65804. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  65805. });
  65806. _this.onAfterRenderObservable.add(function () {
  65807. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  65808. scene.getEngine().cullBackFaces = true;
  65809. scene._mirroredCameraPosition = null;
  65810. delete scene.clipPlane;
  65811. });
  65812. return _this;
  65813. }
  65814. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  65815. get: function () {
  65816. return this._blurRatio;
  65817. },
  65818. set: function (value) {
  65819. if (this._blurRatio === value) {
  65820. return;
  65821. }
  65822. this._blurRatio = value;
  65823. this._preparePostProcesses();
  65824. },
  65825. enumerable: true,
  65826. configurable: true
  65827. });
  65828. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  65829. set: function (value) {
  65830. this._adaptiveBlurKernel = value;
  65831. this._autoComputeBlurKernel();
  65832. },
  65833. enumerable: true,
  65834. configurable: true
  65835. });
  65836. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  65837. set: function (value) {
  65838. this.blurKernelX = value;
  65839. this.blurKernelY = value;
  65840. },
  65841. enumerable: true,
  65842. configurable: true
  65843. });
  65844. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  65845. get: function () {
  65846. return this._blurKernelX;
  65847. },
  65848. set: function (value) {
  65849. if (this._blurKernelX === value) {
  65850. return;
  65851. }
  65852. this._blurKernelX = value;
  65853. this._preparePostProcesses();
  65854. },
  65855. enumerable: true,
  65856. configurable: true
  65857. });
  65858. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  65859. get: function () {
  65860. return this._blurKernelY;
  65861. },
  65862. set: function (value) {
  65863. if (this._blurKernelY === value) {
  65864. return;
  65865. }
  65866. this._blurKernelY = value;
  65867. this._preparePostProcesses();
  65868. },
  65869. enumerable: true,
  65870. configurable: true
  65871. });
  65872. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  65873. var engine = this.getScene().getEngine();
  65874. var dw = this.getRenderWidth() / engine.getRenderWidth();
  65875. var dh = this.getRenderHeight() / engine.getRenderHeight();
  65876. this.blurKernelX = this._adaptiveBlurKernel * dw;
  65877. this.blurKernelY = this._adaptiveBlurKernel * dh;
  65878. };
  65879. MirrorTexture.prototype._onRatioRescale = function () {
  65880. if (this._sizeRatio) {
  65881. this.resize(this._initialSizeParameter);
  65882. if (!this._adaptiveBlurKernel) {
  65883. this._preparePostProcesses();
  65884. }
  65885. }
  65886. if (this._adaptiveBlurKernel) {
  65887. this._autoComputeBlurKernel();
  65888. }
  65889. };
  65890. MirrorTexture.prototype._updateGammaSpace = function () {
  65891. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  65892. };
  65893. MirrorTexture.prototype._preparePostProcesses = function () {
  65894. this.clearPostProcesses(true);
  65895. if (this._blurKernelX && this._blurKernelY) {
  65896. var engine = this.getScene().getEngine();
  65897. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65898. 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);
  65899. this._blurX.autoClear = false;
  65900. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  65901. this._blurX.inputTexture = this._texture;
  65902. }
  65903. else {
  65904. this._blurX.alwaysForcePOT = true;
  65905. }
  65906. 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);
  65907. this._blurY.autoClear = false;
  65908. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  65909. this.addPostProcess(this._blurX);
  65910. this.addPostProcess(this._blurY);
  65911. }
  65912. else {
  65913. if (this._blurY) {
  65914. this.removePostProcess(this._blurY);
  65915. this._blurY.dispose();
  65916. this._blurY = null;
  65917. }
  65918. if (this._blurX) {
  65919. this.removePostProcess(this._blurX);
  65920. this._blurX.dispose();
  65921. this._blurX = null;
  65922. }
  65923. }
  65924. };
  65925. MirrorTexture.prototype.clone = function () {
  65926. var scene = this.getScene();
  65927. if (!scene) {
  65928. return this;
  65929. }
  65930. var textureSize = this.getSize();
  65931. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  65932. // Base texture
  65933. newTexture.hasAlpha = this.hasAlpha;
  65934. newTexture.level = this.level;
  65935. // Mirror Texture
  65936. newTexture.mirrorPlane = this.mirrorPlane.clone();
  65937. if (this.renderList) {
  65938. newTexture.renderList = this.renderList.slice(0);
  65939. }
  65940. return newTexture;
  65941. };
  65942. MirrorTexture.prototype.serialize = function () {
  65943. if (!this.name) {
  65944. return null;
  65945. }
  65946. var serializationObject = _super.prototype.serialize.call(this);
  65947. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  65948. return serializationObject;
  65949. };
  65950. MirrorTexture.prototype.dispose = function () {
  65951. _super.prototype.dispose.call(this);
  65952. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  65953. };
  65954. return MirrorTexture;
  65955. }(BABYLON.RenderTargetTexture));
  65956. BABYLON.MirrorTexture = MirrorTexture;
  65957. })(BABYLON || (BABYLON = {}));
  65958. //# sourceMappingURL=babylon.mirrorTexture.js.map
  65959. var BABYLON;
  65960. (function (BABYLON) {
  65961. /**
  65962. * Creates a refraction texture used by refraction channel of the standard material.
  65963. * @param name the texture name
  65964. * @param size size of the underlying texture
  65965. * @param scene root scene
  65966. */
  65967. var RefractionTexture = /** @class */ (function (_super) {
  65968. __extends(RefractionTexture, _super);
  65969. function RefractionTexture(name, size, scene, generateMipMaps) {
  65970. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  65971. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  65972. _this.depth = 2.0;
  65973. _this.onBeforeRenderObservable.add(function () {
  65974. scene.clipPlane = _this.refractionPlane;
  65975. });
  65976. _this.onAfterRenderObservable.add(function () {
  65977. delete scene.clipPlane;
  65978. });
  65979. return _this;
  65980. }
  65981. RefractionTexture.prototype.clone = function () {
  65982. var scene = this.getScene();
  65983. if (!scene) {
  65984. return this;
  65985. }
  65986. var textureSize = this.getSize();
  65987. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  65988. // Base texture
  65989. newTexture.hasAlpha = this.hasAlpha;
  65990. newTexture.level = this.level;
  65991. // Refraction Texture
  65992. newTexture.refractionPlane = this.refractionPlane.clone();
  65993. if (this.renderList) {
  65994. newTexture.renderList = this.renderList.slice(0);
  65995. }
  65996. newTexture.depth = this.depth;
  65997. return newTexture;
  65998. };
  65999. RefractionTexture.prototype.serialize = function () {
  66000. if (!this.name) {
  66001. return null;
  66002. }
  66003. var serializationObject = _super.prototype.serialize.call(this);
  66004. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  66005. serializationObject.depth = this.depth;
  66006. return serializationObject;
  66007. };
  66008. return RefractionTexture;
  66009. }(BABYLON.RenderTargetTexture));
  66010. BABYLON.RefractionTexture = RefractionTexture;
  66011. })(BABYLON || (BABYLON = {}));
  66012. //# sourceMappingURL=babylon.refractionTexture.js.map
  66013. var BABYLON;
  66014. (function (BABYLON) {
  66015. /**
  66016. * A class extending {BABYLON.Texture} allowing drawing on a texture
  66017. * @see http://doc.babylonjs.com/how_to/dynamictexture
  66018. */
  66019. var DynamicTexture = /** @class */ (function (_super) {
  66020. __extends(DynamicTexture, _super);
  66021. /**
  66022. * Creates a {BABYLON.DynamicTexture}
  66023. * @param name defines the name of the texture
  66024. * @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
  66025. * @param scene defines the scene where you want the texture
  66026. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  66027. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  66028. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  66029. */
  66030. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  66031. if (scene === void 0) { scene = null; }
  66032. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66033. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66034. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  66035. _this.name = name;
  66036. _this._engine = _this.getScene().getEngine();
  66037. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66038. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66039. _this._generateMipMaps = generateMipMaps;
  66040. if (options.getContext) {
  66041. _this._canvas = options;
  66042. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66043. }
  66044. else {
  66045. _this._canvas = document.createElement("canvas");
  66046. if (options.width || options.width === 0) {
  66047. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66048. }
  66049. else {
  66050. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  66051. }
  66052. }
  66053. var textureSize = _this.getSize();
  66054. _this._canvas.width = textureSize.width;
  66055. _this._canvas.height = textureSize.height;
  66056. _this._context = _this._canvas.getContext("2d");
  66057. return _this;
  66058. }
  66059. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  66060. /**
  66061. * Gets the current state of canRescale
  66062. */
  66063. get: function () {
  66064. return true;
  66065. },
  66066. enumerable: true,
  66067. configurable: true
  66068. });
  66069. DynamicTexture.prototype._recreate = function (textureSize) {
  66070. this._canvas.width = textureSize.width;
  66071. this._canvas.height = textureSize.height;
  66072. this.releaseInternalTexture();
  66073. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  66074. };
  66075. /**
  66076. * Scales the texture
  66077. * @param ratio the scale factor to apply to both width and height
  66078. */
  66079. DynamicTexture.prototype.scale = function (ratio) {
  66080. var textureSize = this.getSize();
  66081. textureSize.width *= ratio;
  66082. textureSize.height *= ratio;
  66083. this._recreate(textureSize);
  66084. };
  66085. /**
  66086. * Resizes the texture
  66087. * @param width the new width
  66088. * @param height the new height
  66089. */
  66090. DynamicTexture.prototype.scaleTo = function (width, height) {
  66091. var textureSize = this.getSize();
  66092. textureSize.width = width;
  66093. textureSize.height = height;
  66094. this._recreate(textureSize);
  66095. };
  66096. /**
  66097. * Gets the context of the canvas used by the texture
  66098. * @returns the canvas context of the dynamic texture
  66099. */
  66100. DynamicTexture.prototype.getContext = function () {
  66101. return this._context;
  66102. };
  66103. /**
  66104. * Clears the texture
  66105. */
  66106. DynamicTexture.prototype.clear = function () {
  66107. var size = this.getSize();
  66108. this._context.fillRect(0, 0, size.width, size.height);
  66109. };
  66110. /**
  66111. * Updates the texture
  66112. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66113. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  66114. */
  66115. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  66116. if (premulAlpha === void 0) { premulAlpha = false; }
  66117. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  66118. };
  66119. /**
  66120. * Draws text onto the texture
  66121. * @param text defines the text to be drawn
  66122. * @param x defines the placement of the text from the left
  66123. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  66124. * @param font defines the font to be used with font-style, font-size, font-name
  66125. * @param color defines the color used for the text
  66126. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  66127. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66128. * @param update defines whether texture is immediately update (default is true)
  66129. */
  66130. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  66131. if (update === void 0) { update = true; }
  66132. var size = this.getSize();
  66133. if (clearColor) {
  66134. this._context.fillStyle = clearColor;
  66135. this._context.fillRect(0, 0, size.width, size.height);
  66136. }
  66137. this._context.font = font;
  66138. if (x === null || x === undefined) {
  66139. var textSize = this._context.measureText(text);
  66140. x = (size.width - textSize.width) / 2;
  66141. }
  66142. if (y === null || y === undefined) {
  66143. var fontSize = parseInt((font.replace(/\D/g, '')));
  66144. y = (size.height / 2) + (fontSize / 3.65);
  66145. }
  66146. this._context.fillStyle = color;
  66147. this._context.fillText(text, x, y);
  66148. if (update) {
  66149. this.update(invertY);
  66150. }
  66151. };
  66152. /**
  66153. * Clones the texture
  66154. * @returns the clone of the texture.
  66155. */
  66156. DynamicTexture.prototype.clone = function () {
  66157. var scene = this.getScene();
  66158. if (!scene) {
  66159. return this;
  66160. }
  66161. var textureSize = this.getSize();
  66162. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  66163. // Base texture
  66164. newTexture.hasAlpha = this.hasAlpha;
  66165. newTexture.level = this.level;
  66166. // Dynamic Texture
  66167. newTexture.wrapU = this.wrapU;
  66168. newTexture.wrapV = this.wrapV;
  66169. return newTexture;
  66170. };
  66171. /** @hidden */
  66172. DynamicTexture.prototype._rebuild = function () {
  66173. this.update();
  66174. };
  66175. return DynamicTexture;
  66176. }(BABYLON.Texture));
  66177. BABYLON.DynamicTexture = DynamicTexture;
  66178. })(BABYLON || (BABYLON = {}));
  66179. //# sourceMappingURL=babylon.dynamicTexture.js.map
  66180. var BABYLON;
  66181. (function (BABYLON) {
  66182. var VideoTexture = /** @class */ (function (_super) {
  66183. __extends(VideoTexture, _super);
  66184. /**
  66185. * Creates a video texture.
  66186. * Sample : https://doc.babylonjs.com/how_to/video_texture
  66187. * @param {string | null} name optional name, will detect from video source, if not defined
  66188. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  66189. * @param {BABYLON.Scene} scene is obviously the current scene.
  66190. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  66191. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  66192. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  66193. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  66194. */
  66195. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  66196. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66197. if (invertY === void 0) { invertY = false; }
  66198. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66199. if (settings === void 0) { settings = {
  66200. autoPlay: true,
  66201. loop: true,
  66202. autoUpdateTexture: true,
  66203. }; }
  66204. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66205. _this._onUserActionRequestedObservable = null;
  66206. _this._stillImageCaptured = false;
  66207. _this._poster = false;
  66208. _this._createInternalTexture = function () {
  66209. if (_this._texture != null) {
  66210. if (_this._poster) {
  66211. _this._texture.dispose();
  66212. _this._poster = false;
  66213. }
  66214. else {
  66215. return;
  66216. }
  66217. }
  66218. if (!_this._engine.needPOTTextures ||
  66219. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  66220. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66221. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66222. }
  66223. else {
  66224. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66225. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66226. _this._generateMipMaps = false;
  66227. }
  66228. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  66229. if (!_this.video.autoplay) {
  66230. var oldHandler_1 = _this.video.onplaying;
  66231. var error_1 = false;
  66232. _this.video.onplaying = function () {
  66233. _this.video.onplaying = oldHandler_1;
  66234. _this._texture.isReady = true;
  66235. _this._updateInternalTexture();
  66236. if (!error_1) {
  66237. _this.video.pause();
  66238. }
  66239. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66240. _this.onLoadObservable.notifyObservers(_this);
  66241. }
  66242. };
  66243. var playing = _this.video.play();
  66244. if (playing) {
  66245. playing.then(function () {
  66246. // Everything is good.
  66247. })
  66248. .catch(function () {
  66249. error_1 = true;
  66250. // On Chrome for instance, new policies might prevent playing without user interaction.
  66251. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  66252. _this._onUserActionRequestedObservable.notifyObservers(_this);
  66253. }
  66254. });
  66255. }
  66256. else {
  66257. _this.video.onplaying = oldHandler_1;
  66258. _this._texture.isReady = true;
  66259. _this._updateInternalTexture();
  66260. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66261. _this.onLoadObservable.notifyObservers(_this);
  66262. }
  66263. }
  66264. }
  66265. else {
  66266. _this._texture.isReady = true;
  66267. _this._updateInternalTexture();
  66268. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66269. _this.onLoadObservable.notifyObservers(_this);
  66270. }
  66271. }
  66272. };
  66273. _this.reset = function () {
  66274. if (_this._texture == null) {
  66275. return;
  66276. }
  66277. if (!_this._poster) {
  66278. _this._texture.dispose();
  66279. _this._texture = null;
  66280. }
  66281. };
  66282. _this._updateInternalTexture = function (e) {
  66283. if (_this._texture == null || !_this._texture.isReady) {
  66284. return;
  66285. }
  66286. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  66287. return;
  66288. }
  66289. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  66290. };
  66291. _this._engine = _this.getScene().getEngine();
  66292. _this._generateMipMaps = generateMipMaps;
  66293. _this._samplingMode = samplingMode;
  66294. _this.autoUpdateTexture = settings.autoUpdateTexture;
  66295. _this.name = name || _this._getName(src);
  66296. _this.video = _this._getVideo(src);
  66297. if (settings.poster) {
  66298. _this.video.poster = settings.poster;
  66299. }
  66300. if (settings.autoPlay !== undefined) {
  66301. _this.video.autoplay = settings.autoPlay;
  66302. }
  66303. if (settings.loop !== undefined) {
  66304. _this.video.loop = settings.loop;
  66305. }
  66306. _this.video.setAttribute("playsinline", "");
  66307. _this.video.addEventListener("canplay", _this._createInternalTexture);
  66308. _this.video.addEventListener("paused", _this._updateInternalTexture);
  66309. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  66310. _this.video.addEventListener("emptied", _this.reset);
  66311. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  66312. _this._createInternalTexture();
  66313. }
  66314. if (settings.poster) {
  66315. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  66316. _this._poster = true;
  66317. }
  66318. return _this;
  66319. }
  66320. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  66321. get: function () {
  66322. if (!this._onUserActionRequestedObservable) {
  66323. this._onUserActionRequestedObservable = new BABYLON.Observable();
  66324. }
  66325. return this._onUserActionRequestedObservable;
  66326. },
  66327. enumerable: true,
  66328. configurable: true
  66329. });
  66330. VideoTexture.prototype._getName = function (src) {
  66331. if (src instanceof HTMLVideoElement) {
  66332. return src.currentSrc;
  66333. }
  66334. if (typeof src === "object") {
  66335. return src.toString();
  66336. }
  66337. return src;
  66338. };
  66339. ;
  66340. VideoTexture.prototype._getVideo = function (src) {
  66341. if (src instanceof HTMLVideoElement) {
  66342. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  66343. return src;
  66344. }
  66345. var video = document.createElement("video");
  66346. if (typeof src === "string") {
  66347. BABYLON.Tools.SetCorsBehavior(src, video);
  66348. video.src = src;
  66349. }
  66350. else {
  66351. BABYLON.Tools.SetCorsBehavior(src[0], video);
  66352. src.forEach(function (url) {
  66353. var source = document.createElement("source");
  66354. source.src = url;
  66355. video.appendChild(source);
  66356. });
  66357. }
  66358. return video;
  66359. };
  66360. ;
  66361. /**
  66362. * Internal method to initiate `update`.
  66363. */
  66364. VideoTexture.prototype._rebuild = function () {
  66365. this.update();
  66366. };
  66367. /**
  66368. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  66369. */
  66370. VideoTexture.prototype.update = function () {
  66371. if (!this.autoUpdateTexture) {
  66372. // Expecting user to call `updateTexture` manually
  66373. return;
  66374. }
  66375. this.updateTexture(true);
  66376. };
  66377. /**
  66378. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  66379. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  66380. */
  66381. VideoTexture.prototype.updateTexture = function (isVisible) {
  66382. if (!isVisible) {
  66383. return;
  66384. }
  66385. if (this.video.paused && this._stillImageCaptured) {
  66386. return;
  66387. }
  66388. this._stillImageCaptured = true;
  66389. this._updateInternalTexture();
  66390. };
  66391. /**
  66392. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  66393. * @param url New url.
  66394. */
  66395. VideoTexture.prototype.updateURL = function (url) {
  66396. this.video.src = url;
  66397. };
  66398. VideoTexture.prototype.dispose = function () {
  66399. _super.prototype.dispose.call(this);
  66400. if (this._onUserActionRequestedObservable) {
  66401. this._onUserActionRequestedObservable.clear();
  66402. this._onUserActionRequestedObservable = null;
  66403. }
  66404. this.video.removeEventListener("canplay", this._createInternalTexture);
  66405. this.video.removeEventListener("paused", this._updateInternalTexture);
  66406. this.video.removeEventListener("seeked", this._updateInternalTexture);
  66407. this.video.removeEventListener("emptied", this.reset);
  66408. this.video.pause();
  66409. };
  66410. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  66411. var video = document.createElement("video");
  66412. video.setAttribute('autoplay', '');
  66413. video.setAttribute('muted', '');
  66414. video.setAttribute('playsinline', '');
  66415. var constraintsDeviceId;
  66416. if (constraints && constraints.deviceId) {
  66417. constraintsDeviceId = {
  66418. exact: constraints.deviceId,
  66419. };
  66420. }
  66421. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  66422. if (navigator.mediaDevices) {
  66423. navigator.mediaDevices.getUserMedia({ video: constraints })
  66424. .then(function (stream) {
  66425. if (video.mozSrcObject !== undefined) {
  66426. // hack for Firefox < 19
  66427. video.mozSrcObject = stream;
  66428. }
  66429. else {
  66430. video.srcObject = stream;
  66431. }
  66432. var onPlaying = function () {
  66433. if (onReady) {
  66434. onReady(new VideoTexture("video", video, scene, true, true));
  66435. }
  66436. video.removeEventListener("playing", onPlaying);
  66437. };
  66438. video.addEventListener("playing", onPlaying);
  66439. video.play();
  66440. })
  66441. .catch(function (err) {
  66442. BABYLON.Tools.Error(err.name);
  66443. });
  66444. }
  66445. else {
  66446. navigator.getUserMedia =
  66447. navigator.getUserMedia ||
  66448. navigator.webkitGetUserMedia ||
  66449. navigator.mozGetUserMedia ||
  66450. navigator.msGetUserMedia;
  66451. if (navigator.getUserMedia) {
  66452. navigator.getUserMedia({
  66453. video: {
  66454. deviceId: constraintsDeviceId,
  66455. width: {
  66456. min: (constraints && constraints.minWidth) || 256,
  66457. max: (constraints && constraints.maxWidth) || 640,
  66458. },
  66459. height: {
  66460. min: (constraints && constraints.minHeight) || 256,
  66461. max: (constraints && constraints.maxHeight) || 480,
  66462. },
  66463. },
  66464. }, function (stream) {
  66465. if (video.mozSrcObject !== undefined) {
  66466. // hack for Firefox < 19
  66467. video.mozSrcObject = stream;
  66468. }
  66469. else {
  66470. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  66471. }
  66472. video.play();
  66473. if (onReady) {
  66474. onReady(new VideoTexture("video", video, scene, true, true));
  66475. }
  66476. }, function (e) {
  66477. BABYLON.Tools.Error(e.name);
  66478. });
  66479. }
  66480. }
  66481. };
  66482. return VideoTexture;
  66483. }(BABYLON.Texture));
  66484. BABYLON.VideoTexture = VideoTexture;
  66485. })(BABYLON || (BABYLON = {}));
  66486. //# sourceMappingURL=babylon.videoTexture.js.map
  66487. var BABYLON;
  66488. (function (BABYLON) {
  66489. var RawTexture = /** @class */ (function (_super) {
  66490. __extends(RawTexture, _super);
  66491. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  66492. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66493. if (invertY === void 0) { invertY = false; }
  66494. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66495. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66496. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66497. _this.format = format;
  66498. _this._engine = scene.getEngine();
  66499. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  66500. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66501. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66502. return _this;
  66503. }
  66504. RawTexture.prototype.update = function (data) {
  66505. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66506. };
  66507. // Statics
  66508. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66509. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66510. if (invertY === void 0) { invertY = false; }
  66511. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66512. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  66513. };
  66514. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66515. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66516. if (invertY === void 0) { invertY = false; }
  66517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66518. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66519. };
  66520. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66521. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66522. if (invertY === void 0) { invertY = false; }
  66523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66524. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66525. };
  66526. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66527. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66528. if (invertY === void 0) { invertY = false; }
  66529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66530. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66531. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  66532. };
  66533. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66534. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66535. if (invertY === void 0) { invertY = false; }
  66536. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66537. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66538. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  66539. };
  66540. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66541. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66542. if (invertY === void 0) { invertY = false; }
  66543. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66544. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66545. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  66546. };
  66547. return RawTexture;
  66548. }(BABYLON.Texture));
  66549. BABYLON.RawTexture = RawTexture;
  66550. })(BABYLON || (BABYLON = {}));
  66551. //# sourceMappingURL=babylon.rawTexture.js.map
  66552. var BABYLON;
  66553. (function (BABYLON) {
  66554. /**
  66555. * Class used to store 3D textures containing user data
  66556. */
  66557. var RawTexture3D = /** @class */ (function (_super) {
  66558. __extends(RawTexture3D, _super);
  66559. /**
  66560. * Create a new RawTexture3D
  66561. * @param data defines the data of the texture
  66562. * @param width defines the width of the texture
  66563. * @param height defines the height of the texture
  66564. * @param depth defines the depth of the texture
  66565. * @param format defines the texture format to use
  66566. * @param scene defines the hosting scene
  66567. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  66568. * @param invertY defines if texture must be stored with Y axis inverted
  66569. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  66570. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  66571. */
  66572. function RawTexture3D(data, width, height, depth,
  66573. /** Gets or sets the texture format to use */
  66574. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  66575. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66576. if (invertY === void 0) { invertY = false; }
  66577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66578. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66579. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66580. _this.format = format;
  66581. _this._engine = scene.getEngine();
  66582. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  66583. _this.is3D = true;
  66584. return _this;
  66585. }
  66586. /**
  66587. * Update the texture with new data
  66588. * @param data defines the data to store in the texture
  66589. */
  66590. RawTexture3D.prototype.update = function (data) {
  66591. if (!this._texture) {
  66592. return;
  66593. }
  66594. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66595. };
  66596. return RawTexture3D;
  66597. }(BABYLON.Texture));
  66598. BABYLON.RawTexture3D = RawTexture3D;
  66599. })(BABYLON || (BABYLON = {}));
  66600. //# sourceMappingURL=babylon.rawTexture3D.js.map
  66601. var BABYLON;
  66602. (function (BABYLON) {
  66603. /**
  66604. * PostProcessManager is used to manage one or more post processes or post process pipelines
  66605. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66606. */
  66607. var PostProcessManager = /** @class */ (function () {
  66608. /**
  66609. * Creates a new instance PostProcess
  66610. * @param scene The scene that the post process is associated with.
  66611. */
  66612. function PostProcessManager(scene) {
  66613. this._vertexBuffers = {};
  66614. this._scene = scene;
  66615. }
  66616. PostProcessManager.prototype._prepareBuffers = function () {
  66617. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  66618. return;
  66619. }
  66620. // VBO
  66621. var vertices = [];
  66622. vertices.push(1, 1);
  66623. vertices.push(-1, 1);
  66624. vertices.push(-1, -1);
  66625. vertices.push(1, -1);
  66626. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66627. this._buildIndexBuffer();
  66628. };
  66629. PostProcessManager.prototype._buildIndexBuffer = function () {
  66630. // Indices
  66631. var indices = [];
  66632. indices.push(0);
  66633. indices.push(1);
  66634. indices.push(2);
  66635. indices.push(0);
  66636. indices.push(2);
  66637. indices.push(3);
  66638. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  66639. };
  66640. /**
  66641. * Rebuilds the vertex buffers of the manager.
  66642. */
  66643. PostProcessManager.prototype._rebuild = function () {
  66644. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66645. if (!vb) {
  66646. return;
  66647. }
  66648. vb._rebuild();
  66649. this._buildIndexBuffer();
  66650. };
  66651. // Methods
  66652. /**
  66653. * Prepares a frame to be run through a post process.
  66654. * @param sourceTexture The input texture to the post procesess. (default: null)
  66655. * @param postProcesses An array of post processes to be run. (default: null)
  66656. * @returns True if the post processes were able to be run.
  66657. */
  66658. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  66659. if (sourceTexture === void 0) { sourceTexture = null; }
  66660. if (postProcesses === void 0) { postProcesses = null; }
  66661. var camera = this._scene.activeCamera;
  66662. if (!camera) {
  66663. return false;
  66664. }
  66665. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66666. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66667. return false;
  66668. }
  66669. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  66670. return true;
  66671. };
  66672. /**
  66673. * Manually render a set of post processes to a texture.
  66674. * @param postProcesses An array of post processes to be run.
  66675. * @param targetTexture The target texture to render to.
  66676. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  66677. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  66678. * @param lodLevel defines which lod of the texture to render to
  66679. */
  66680. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  66681. if (targetTexture === void 0) { targetTexture = null; }
  66682. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66683. if (faceIndex === void 0) { faceIndex = 0; }
  66684. if (lodLevel === void 0) { lodLevel = 0; }
  66685. var engine = this._scene.getEngine();
  66686. for (var index = 0; index < postProcesses.length; index++) {
  66687. if (index < postProcesses.length - 1) {
  66688. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  66689. }
  66690. else {
  66691. if (targetTexture) {
  66692. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  66693. }
  66694. else {
  66695. engine.restoreDefaultFramebuffer();
  66696. }
  66697. }
  66698. var pp = postProcesses[index];
  66699. var effect = pp.apply();
  66700. if (effect) {
  66701. pp.onBeforeRenderObservable.notifyObservers(effect);
  66702. // VBOs
  66703. this._prepareBuffers();
  66704. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66705. // Draw order
  66706. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66707. pp.onAfterRenderObservable.notifyObservers(effect);
  66708. }
  66709. }
  66710. // Restore depth buffer
  66711. engine.setDepthBuffer(true);
  66712. engine.setDepthWrite(true);
  66713. };
  66714. /**
  66715. * Finalize the result of the output of the postprocesses.
  66716. * @param doNotPresent If true the result will not be displayed to the screen.
  66717. * @param targetTexture The target texture to render to.
  66718. * @param faceIndex The index of the face to bind the target texture to.
  66719. * @param postProcesses The array of post processes to render.
  66720. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  66721. */
  66722. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  66723. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66724. var camera = this._scene.activeCamera;
  66725. if (!camera) {
  66726. return;
  66727. }
  66728. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66729. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66730. return;
  66731. }
  66732. var engine = this._scene.getEngine();
  66733. for (var index = 0, len = postProcesses.length; index < len; index++) {
  66734. var pp = postProcesses[index];
  66735. if (index < len - 1) {
  66736. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  66737. }
  66738. else {
  66739. if (targetTexture) {
  66740. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  66741. pp._outputTexture = targetTexture;
  66742. }
  66743. else {
  66744. engine.restoreDefaultFramebuffer();
  66745. pp._outputTexture = null;
  66746. }
  66747. }
  66748. if (doNotPresent) {
  66749. break;
  66750. }
  66751. var effect = pp.apply();
  66752. if (effect) {
  66753. pp.onBeforeRenderObservable.notifyObservers(effect);
  66754. // VBOs
  66755. this._prepareBuffers();
  66756. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66757. // Draw order
  66758. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66759. pp.onAfterRenderObservable.notifyObservers(effect);
  66760. }
  66761. }
  66762. // Restore states
  66763. engine.setDepthBuffer(true);
  66764. engine.setDepthWrite(true);
  66765. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66766. };
  66767. /**
  66768. * Disposes of the post process manager.
  66769. */
  66770. PostProcessManager.prototype.dispose = function () {
  66771. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66772. if (buffer) {
  66773. buffer.dispose();
  66774. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66775. }
  66776. if (this._indexBuffer) {
  66777. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66778. this._indexBuffer = null;
  66779. }
  66780. };
  66781. return PostProcessManager;
  66782. }());
  66783. BABYLON.PostProcessManager = PostProcessManager;
  66784. })(BABYLON || (BABYLON = {}));
  66785. //# sourceMappingURL=babylon.postProcessManager.js.map
  66786. var BABYLON;
  66787. (function (BABYLON) {
  66788. /**
  66789. * PostProcess can be used to apply a shader to a texture after it has been rendered
  66790. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66791. */
  66792. var PostProcess = /** @class */ (function () {
  66793. /**
  66794. * Creates a new instance PostProcess
  66795. * @param name The name of the PostProcess.
  66796. * @param fragmentUrl The url of the fragment shader to be used.
  66797. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  66798. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  66799. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66800. * @param camera The camera to apply the render pass to.
  66801. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66802. * @param engine The engine which the post process will be applied. (default: current engine)
  66803. * @param reusable If the post process can be reused on the same frame. (default: false)
  66804. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  66805. * @param textureType Type of textures used when performing the post process. (default: 0)
  66806. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  66807. * @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
  66808. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  66809. */
  66810. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  66811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  66812. if (defines === void 0) { defines = null; }
  66813. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66814. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  66815. if (blockCompilation === void 0) { blockCompilation = false; }
  66816. this.name = name;
  66817. /**
  66818. * Width of the texture to apply the post process on
  66819. */
  66820. this.width = -1;
  66821. /**
  66822. * Height of the texture to apply the post process on
  66823. */
  66824. this.height = -1;
  66825. /**
  66826. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  66827. */
  66828. this._outputTexture = null;
  66829. /**
  66830. * If the buffer needs to be cleared before applying the post process. (default: true)
  66831. * Should be set to false if shader will overwrite all previous pixels.
  66832. */
  66833. this.autoClear = true;
  66834. /**
  66835. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  66836. */
  66837. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  66838. /**
  66839. * Animations to be used for the post processing
  66840. */
  66841. this.animations = new Array();
  66842. /**
  66843. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  66844. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  66845. */
  66846. this.enablePixelPerfectMode = false;
  66847. /**
  66848. * Force the postprocess to be applied without taking in account viewport
  66849. */
  66850. this.forceFullscreenViewport = true;
  66851. /**
  66852. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  66853. *
  66854. * | Value | Type | Description |
  66855. * | ----- | ----------------------------------- | ----------- |
  66856. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  66857. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  66858. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  66859. *
  66860. */
  66861. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  66862. /**
  66863. * Force textures to be a power of two (default: false)
  66864. */
  66865. this.alwaysForcePOT = false;
  66866. /**
  66867. * Number of sample textures (default: 1)
  66868. */
  66869. this.samples = 1;
  66870. /**
  66871. * Modify the scale of the post process to be the same as the viewport (default: false)
  66872. */
  66873. this.adaptScaleToCurrentViewport = false;
  66874. this._reusable = false;
  66875. /**
  66876. * Smart array of input and output textures for the post process.
  66877. */
  66878. this._textures = new BABYLON.SmartArray(2);
  66879. /**
  66880. * The index in _textures that corresponds to the output texture.
  66881. */
  66882. this._currentRenderTextureInd = 0;
  66883. this._scaleRatio = new BABYLON.Vector2(1, 1);
  66884. this._texelSize = BABYLON.Vector2.Zero();
  66885. // Events
  66886. /**
  66887. * An event triggered when the postprocess is activated.
  66888. */
  66889. this.onActivateObservable = new BABYLON.Observable();
  66890. /**
  66891. * An event triggered when the postprocess changes its size.
  66892. */
  66893. this.onSizeChangedObservable = new BABYLON.Observable();
  66894. /**
  66895. * An event triggered when the postprocess applies its effect.
  66896. */
  66897. this.onApplyObservable = new BABYLON.Observable();
  66898. /**
  66899. * An event triggered before rendering the postprocess
  66900. */
  66901. this.onBeforeRenderObservable = new BABYLON.Observable();
  66902. /**
  66903. * An event triggered after rendering the postprocess
  66904. */
  66905. this.onAfterRenderObservable = new BABYLON.Observable();
  66906. if (camera != null) {
  66907. this._camera = camera;
  66908. this._scene = camera.getScene();
  66909. camera.attachPostProcess(this);
  66910. this._engine = this._scene.getEngine();
  66911. this._scene.postProcesses.push(this);
  66912. }
  66913. else if (engine) {
  66914. this._engine = engine;
  66915. this._engine.postProcesses.push(this);
  66916. }
  66917. this._options = options;
  66918. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  66919. this._reusable = reusable || false;
  66920. this._textureType = textureType;
  66921. this._samplers = samplers || [];
  66922. this._samplers.push("textureSampler");
  66923. this._fragmentUrl = fragmentUrl;
  66924. this._vertexUrl = vertexUrl;
  66925. this._parameters = parameters || [];
  66926. this._parameters.push("scale");
  66927. this._indexParameters = indexParameters;
  66928. if (!blockCompilation) {
  66929. this.updateEffect(defines);
  66930. }
  66931. }
  66932. Object.defineProperty(PostProcess.prototype, "onActivate", {
  66933. /**
  66934. * A function that is added to the onActivateObservable
  66935. */
  66936. set: function (callback) {
  66937. if (this._onActivateObserver) {
  66938. this.onActivateObservable.remove(this._onActivateObserver);
  66939. }
  66940. if (callback) {
  66941. this._onActivateObserver = this.onActivateObservable.add(callback);
  66942. }
  66943. },
  66944. enumerable: true,
  66945. configurable: true
  66946. });
  66947. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  66948. /**
  66949. * A function that is added to the onSizeChangedObservable
  66950. */
  66951. set: function (callback) {
  66952. if (this._onSizeChangedObserver) {
  66953. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  66954. }
  66955. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  66956. },
  66957. enumerable: true,
  66958. configurable: true
  66959. });
  66960. Object.defineProperty(PostProcess.prototype, "onApply", {
  66961. /**
  66962. * A function that is added to the onApplyObservable
  66963. */
  66964. set: function (callback) {
  66965. if (this._onApplyObserver) {
  66966. this.onApplyObservable.remove(this._onApplyObserver);
  66967. }
  66968. this._onApplyObserver = this.onApplyObservable.add(callback);
  66969. },
  66970. enumerable: true,
  66971. configurable: true
  66972. });
  66973. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  66974. /**
  66975. * A function that is added to the onBeforeRenderObservable
  66976. */
  66977. set: function (callback) {
  66978. if (this._onBeforeRenderObserver) {
  66979. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66980. }
  66981. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66982. },
  66983. enumerable: true,
  66984. configurable: true
  66985. });
  66986. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  66987. /**
  66988. * A function that is added to the onAfterRenderObservable
  66989. */
  66990. set: function (callback) {
  66991. if (this._onAfterRenderObserver) {
  66992. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66993. }
  66994. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66995. },
  66996. enumerable: true,
  66997. configurable: true
  66998. });
  66999. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  67000. /**
  67001. * 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
  67002. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  67003. */
  67004. get: function () {
  67005. return this._textures.data[this._currentRenderTextureInd];
  67006. },
  67007. set: function (value) {
  67008. this._forcedOutputTexture = value;
  67009. },
  67010. enumerable: true,
  67011. configurable: true
  67012. });
  67013. /**
  67014. * Gets the camera which post process is applied to.
  67015. * @returns The camera the post process is applied to.
  67016. */
  67017. PostProcess.prototype.getCamera = function () {
  67018. return this._camera;
  67019. };
  67020. Object.defineProperty(PostProcess.prototype, "texelSize", {
  67021. /**
  67022. * Gets the texel size of the postprocess.
  67023. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  67024. */
  67025. get: function () {
  67026. if (this._shareOutputWithPostProcess) {
  67027. return this._shareOutputWithPostProcess.texelSize;
  67028. }
  67029. if (this._forcedOutputTexture) {
  67030. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  67031. }
  67032. return this._texelSize;
  67033. },
  67034. enumerable: true,
  67035. configurable: true
  67036. });
  67037. /**
  67038. * Gets the engine which this post process belongs to.
  67039. * @returns The engine the post process was enabled with.
  67040. */
  67041. PostProcess.prototype.getEngine = function () {
  67042. return this._engine;
  67043. };
  67044. /**
  67045. * The effect that is created when initializing the post process.
  67046. * @returns The created effect corrisponding the the postprocess.
  67047. */
  67048. PostProcess.prototype.getEffect = function () {
  67049. return this._effect;
  67050. };
  67051. /**
  67052. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  67053. * @param postProcess The post process to share the output with.
  67054. * @returns This post process.
  67055. */
  67056. PostProcess.prototype.shareOutputWith = function (postProcess) {
  67057. this._disposeTextures();
  67058. this._shareOutputWithPostProcess = postProcess;
  67059. return this;
  67060. };
  67061. /**
  67062. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  67063. * This should be called if the post process that shares output with this post process is disabled/disposed.
  67064. */
  67065. PostProcess.prototype.useOwnOutput = function () {
  67066. if (this._textures.length == 0) {
  67067. this._textures = new BABYLON.SmartArray(2);
  67068. }
  67069. this._shareOutputWithPostProcess = null;
  67070. };
  67071. /**
  67072. * Updates the effect with the current post process compile time values and recompiles the shader.
  67073. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  67074. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  67075. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  67076. * @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
  67077. * @param onCompiled Called when the shader has been compiled.
  67078. * @param onError Called if there is an error when compiling a shader.
  67079. */
  67080. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  67081. if (defines === void 0) { defines = null; }
  67082. if (uniforms === void 0) { uniforms = null; }
  67083. if (samplers === void 0) { samplers = null; }
  67084. 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);
  67085. };
  67086. /**
  67087. * The post process is reusable if it can be used multiple times within one frame.
  67088. * @returns If the post process is reusable
  67089. */
  67090. PostProcess.prototype.isReusable = function () {
  67091. return this._reusable;
  67092. };
  67093. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  67094. PostProcess.prototype.markTextureDirty = function () {
  67095. this.width = -1;
  67096. };
  67097. /**
  67098. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  67099. * 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.
  67100. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  67101. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  67102. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  67103. * @returns The target texture that was bound to be written to.
  67104. */
  67105. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  67106. var _this = this;
  67107. if (sourceTexture === void 0) { sourceTexture = null; }
  67108. camera = camera || this._camera;
  67109. var scene = camera.getScene();
  67110. var engine = scene.getEngine();
  67111. var maxSize = engine.getCaps().maxTextureSize;
  67112. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  67113. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  67114. // 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
  67115. var webVRCamera = camera.parent;
  67116. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  67117. requiredWidth /= 2;
  67118. }
  67119. var desiredWidth = (this._options.width || requiredWidth);
  67120. var desiredHeight = this._options.height || requiredHeight;
  67121. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  67122. if (this.adaptScaleToCurrentViewport) {
  67123. var currentViewport = engine.currentViewport;
  67124. if (currentViewport) {
  67125. desiredWidth *= currentViewport.width;
  67126. desiredHeight *= currentViewport.height;
  67127. }
  67128. }
  67129. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  67130. if (!this._options.width) {
  67131. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  67132. }
  67133. if (!this._options.height) {
  67134. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  67135. }
  67136. }
  67137. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  67138. if (this._textures.length > 0) {
  67139. for (var i = 0; i < this._textures.length; i++) {
  67140. this._engine._releaseTexture(this._textures.data[i]);
  67141. }
  67142. this._textures.reset();
  67143. }
  67144. this.width = desiredWidth;
  67145. this.height = desiredHeight;
  67146. var textureSize = { width: this.width, height: this.height };
  67147. var textureOptions = {
  67148. generateMipMaps: false,
  67149. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  67150. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  67151. samplingMode: this.renderTargetSamplingMode,
  67152. type: this._textureType
  67153. };
  67154. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67155. if (this._reusable) {
  67156. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67157. }
  67158. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  67159. this.onSizeChangedObservable.notifyObservers(this);
  67160. }
  67161. this._textures.forEach(function (texture) {
  67162. if (texture.samples !== _this.samples) {
  67163. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  67164. }
  67165. });
  67166. }
  67167. var target;
  67168. if (this._shareOutputWithPostProcess) {
  67169. target = this._shareOutputWithPostProcess.inputTexture;
  67170. }
  67171. else if (this._forcedOutputTexture) {
  67172. target = this._forcedOutputTexture;
  67173. this.width = this._forcedOutputTexture.width;
  67174. this.height = this._forcedOutputTexture.height;
  67175. }
  67176. else {
  67177. target = this.inputTexture;
  67178. }
  67179. // Bind the input of this post process to be used as the output of the previous post process.
  67180. if (this.enablePixelPerfectMode) {
  67181. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  67182. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  67183. }
  67184. else {
  67185. this._scaleRatio.copyFromFloats(1, 1);
  67186. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  67187. }
  67188. this.onActivateObservable.notifyObservers(camera);
  67189. // Clear
  67190. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  67191. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  67192. }
  67193. if (this._reusable) {
  67194. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  67195. }
  67196. return target;
  67197. };
  67198. Object.defineProperty(PostProcess.prototype, "isSupported", {
  67199. /**
  67200. * If the post process is supported.
  67201. */
  67202. get: function () {
  67203. return this._effect.isSupported;
  67204. },
  67205. enumerable: true,
  67206. configurable: true
  67207. });
  67208. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  67209. /**
  67210. * The aspect ratio of the output texture.
  67211. */
  67212. get: function () {
  67213. if (this._shareOutputWithPostProcess) {
  67214. return this._shareOutputWithPostProcess.aspectRatio;
  67215. }
  67216. if (this._forcedOutputTexture) {
  67217. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  67218. }
  67219. return this.width / this.height;
  67220. },
  67221. enumerable: true,
  67222. configurable: true
  67223. });
  67224. /**
  67225. * Get a value indicating if the post-process is ready to be used
  67226. * @returns true if the post-process is ready (shader is compiled)
  67227. */
  67228. PostProcess.prototype.isReady = function () {
  67229. return this._effect && this._effect.isReady();
  67230. };
  67231. /**
  67232. * Binds all textures and uniforms to the shader, this will be run on every pass.
  67233. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  67234. */
  67235. PostProcess.prototype.apply = function () {
  67236. // Check
  67237. if (!this._effect || !this._effect.isReady())
  67238. return null;
  67239. // States
  67240. this._engine.enableEffect(this._effect);
  67241. this._engine.setState(false);
  67242. this._engine.setDepthBuffer(false);
  67243. this._engine.setDepthWrite(false);
  67244. // Alpha
  67245. this._engine.setAlphaMode(this.alphaMode);
  67246. if (this.alphaConstants) {
  67247. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  67248. }
  67249. // Bind the output texture of the preivous post process as the input to this post process.
  67250. var source;
  67251. if (this._shareOutputWithPostProcess) {
  67252. source = this._shareOutputWithPostProcess.inputTexture;
  67253. }
  67254. else if (this._forcedOutputTexture) {
  67255. source = this._forcedOutputTexture;
  67256. }
  67257. else {
  67258. source = this.inputTexture;
  67259. }
  67260. this._effect._bindTexture("textureSampler", source);
  67261. // Parameters
  67262. this._effect.setVector2("scale", this._scaleRatio);
  67263. this.onApplyObservable.notifyObservers(this._effect);
  67264. return this._effect;
  67265. };
  67266. PostProcess.prototype._disposeTextures = function () {
  67267. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  67268. return;
  67269. }
  67270. if (this._textures.length > 0) {
  67271. for (var i = 0; i < this._textures.length; i++) {
  67272. this._engine._releaseTexture(this._textures.data[i]);
  67273. }
  67274. }
  67275. this._textures.dispose();
  67276. };
  67277. /**
  67278. * Disposes the post process.
  67279. * @param camera The camera to dispose the post process on.
  67280. */
  67281. PostProcess.prototype.dispose = function (camera) {
  67282. camera = camera || this._camera;
  67283. this._disposeTextures();
  67284. if (this._scene) {
  67285. var index_1 = this._scene.postProcesses.indexOf(this);
  67286. if (index_1 !== -1) {
  67287. this._scene.postProcesses.splice(index_1, 1);
  67288. }
  67289. }
  67290. else {
  67291. var index_2 = this._engine.postProcesses.indexOf(this);
  67292. if (index_2 !== -1) {
  67293. this._engine.postProcesses.splice(index_2, 1);
  67294. }
  67295. }
  67296. if (!camera) {
  67297. return;
  67298. }
  67299. camera.detachPostProcess(this);
  67300. var index = camera._postProcesses.indexOf(this);
  67301. if (index === 0 && camera._postProcesses.length > 0) {
  67302. var firstPostProcess = this._camera._getFirstPostProcess();
  67303. if (firstPostProcess) {
  67304. firstPostProcess.markTextureDirty();
  67305. }
  67306. }
  67307. this.onActivateObservable.clear();
  67308. this.onAfterRenderObservable.clear();
  67309. this.onApplyObservable.clear();
  67310. this.onBeforeRenderObservable.clear();
  67311. this.onSizeChangedObservable.clear();
  67312. };
  67313. return PostProcess;
  67314. }());
  67315. BABYLON.PostProcess = PostProcess;
  67316. })(BABYLON || (BABYLON = {}));
  67317. //# sourceMappingURL=babylon.postProcess.js.map
  67318. var BABYLON;
  67319. (function (BABYLON) {
  67320. var PassPostProcess = /** @class */ (function (_super) {
  67321. __extends(PassPostProcess, _super);
  67322. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67323. if (camera === void 0) { camera = null; }
  67324. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67325. if (blockCompilation === void 0) { blockCompilation = false; }
  67326. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  67327. }
  67328. return PassPostProcess;
  67329. }(BABYLON.PostProcess));
  67330. BABYLON.PassPostProcess = PassPostProcess;
  67331. })(BABYLON || (BABYLON = {}));
  67332. //# sourceMappingURL=babylon.passPostProcess.js.map
  67333. var __assign = (this && this.__assign) || Object.assign || function(t) {
  67334. for (var s, i = 1, n = arguments.length; i < n; i++) {
  67335. s = arguments[i];
  67336. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  67337. t[p] = s[p];
  67338. }
  67339. return t;
  67340. };
  67341. var BABYLON;
  67342. (function (BABYLON) {
  67343. /**
  67344. * Default implementation IShadowGenerator.
  67345. * This is the main object responsible of generating shadows in the framework.
  67346. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  67347. */
  67348. var ShadowGenerator = /** @class */ (function () {
  67349. /**
  67350. * Creates a ShadowGenerator object.
  67351. * A ShadowGenerator is the required tool to use the shadows.
  67352. * Each light casting shadows needs to use its own ShadowGenerator.
  67353. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  67354. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  67355. * @param light The light object generating the shadows.
  67356. * @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.
  67357. */
  67358. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  67359. this._bias = 0.00005;
  67360. this._normalBias = 0;
  67361. this._blurBoxOffset = 1;
  67362. this._blurScale = 2;
  67363. this._blurKernel = 1;
  67364. this._useKernelBlur = false;
  67365. this._filter = ShadowGenerator.FILTER_NONE;
  67366. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  67367. this._contactHardeningLightSizeUVRatio = 0.1;
  67368. this._darkness = 0;
  67369. this._transparencyShadow = false;
  67370. /**
  67371. * Controls the extent to which the shadows fade out at the edge of the frustum
  67372. * Used only by directionals and spots
  67373. */
  67374. this.frustumEdgeFalloff = 0;
  67375. /**
  67376. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  67377. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  67378. * It might on the other hand introduce peter panning.
  67379. */
  67380. this.forceBackFacesOnly = false;
  67381. this._lightDirection = BABYLON.Vector3.Zero();
  67382. this._viewMatrix = BABYLON.Matrix.Zero();
  67383. this._projectionMatrix = BABYLON.Matrix.Zero();
  67384. this._transformMatrix = BABYLON.Matrix.Zero();
  67385. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67386. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67387. this._currentFaceIndex = 0;
  67388. this._currentFaceIndexCache = 0;
  67389. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  67390. this._mapSize = mapSize;
  67391. this._light = light;
  67392. this._scene = light.getScene();
  67393. light._shadowGenerator = this;
  67394. // Texture type fallback from float to int if not supported.
  67395. var caps = this._scene.getEngine().getCaps();
  67396. if (!useFullFloatFirst) {
  67397. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67398. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67399. }
  67400. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67401. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67402. }
  67403. else {
  67404. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67405. }
  67406. }
  67407. else {
  67408. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67409. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67410. }
  67411. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67412. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67413. }
  67414. else {
  67415. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67416. }
  67417. }
  67418. this._initializeGenerator();
  67419. this._applyFilterValues();
  67420. }
  67421. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  67422. /**
  67423. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  67424. */
  67425. get: function () {
  67426. return this._bias;
  67427. },
  67428. /**
  67429. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  67430. */
  67431. set: function (bias) {
  67432. this._bias = bias;
  67433. },
  67434. enumerable: true,
  67435. configurable: true
  67436. });
  67437. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  67438. /**
  67439. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67440. */
  67441. get: function () {
  67442. return this._normalBias;
  67443. },
  67444. /**
  67445. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67446. */
  67447. set: function (normalBias) {
  67448. this._normalBias = normalBias;
  67449. },
  67450. enumerable: true,
  67451. configurable: true
  67452. });
  67453. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  67454. /**
  67455. * Gets the blur box offset: offset applied during the blur pass.
  67456. * Only usefull if useKernelBlur = false
  67457. */
  67458. get: function () {
  67459. return this._blurBoxOffset;
  67460. },
  67461. /**
  67462. * Sets the blur box offset: offset applied during the blur pass.
  67463. * Only usefull if useKernelBlur = false
  67464. */
  67465. set: function (value) {
  67466. if (this._blurBoxOffset === value) {
  67467. return;
  67468. }
  67469. this._blurBoxOffset = value;
  67470. this._disposeBlurPostProcesses();
  67471. },
  67472. enumerable: true,
  67473. configurable: true
  67474. });
  67475. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  67476. /**
  67477. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  67478. * 2 means half of the size.
  67479. */
  67480. get: function () {
  67481. return this._blurScale;
  67482. },
  67483. /**
  67484. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  67485. * 2 means half of the size.
  67486. */
  67487. set: function (value) {
  67488. if (this._blurScale === value) {
  67489. return;
  67490. }
  67491. this._blurScale = value;
  67492. this._disposeBlurPostProcesses();
  67493. },
  67494. enumerable: true,
  67495. configurable: true
  67496. });
  67497. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  67498. /**
  67499. * Gets the blur kernel: kernel size of the blur pass.
  67500. * Only usefull if useKernelBlur = true
  67501. */
  67502. get: function () {
  67503. return this._blurKernel;
  67504. },
  67505. /**
  67506. * Sets the blur kernel: kernel size of the blur pass.
  67507. * Only usefull if useKernelBlur = true
  67508. */
  67509. set: function (value) {
  67510. if (this._blurKernel === value) {
  67511. return;
  67512. }
  67513. this._blurKernel = value;
  67514. this._disposeBlurPostProcesses();
  67515. },
  67516. enumerable: true,
  67517. configurable: true
  67518. });
  67519. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  67520. /**
  67521. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  67522. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67523. */
  67524. get: function () {
  67525. return this._useKernelBlur;
  67526. },
  67527. /**
  67528. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  67529. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67530. */
  67531. set: function (value) {
  67532. if (this._useKernelBlur === value) {
  67533. return;
  67534. }
  67535. this._useKernelBlur = value;
  67536. this._disposeBlurPostProcesses();
  67537. },
  67538. enumerable: true,
  67539. configurable: true
  67540. });
  67541. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  67542. /**
  67543. * Gets the depth scale used in ESM mode.
  67544. */
  67545. get: function () {
  67546. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  67547. },
  67548. /**
  67549. * Sets the depth scale used in ESM mode.
  67550. * This can override the scale stored on the light.
  67551. */
  67552. set: function (value) {
  67553. this._depthScale = value;
  67554. },
  67555. enumerable: true,
  67556. configurable: true
  67557. });
  67558. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  67559. /**
  67560. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  67561. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67562. */
  67563. get: function () {
  67564. return this._filter;
  67565. },
  67566. /**
  67567. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  67568. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67569. */
  67570. set: function (value) {
  67571. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  67572. if (this._light.needCube()) {
  67573. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67574. this.useExponentialShadowMap = true;
  67575. return;
  67576. }
  67577. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67578. this.useCloseExponentialShadowMap = true;
  67579. return;
  67580. }
  67581. // PCF on cubemap would also be expensive
  67582. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67583. this.usePoissonSampling = true;
  67584. return;
  67585. }
  67586. }
  67587. // Weblg1 fallback for PCF.
  67588. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67589. if (this._scene.getEngine().webGLVersion === 1) {
  67590. this.usePoissonSampling = true;
  67591. return;
  67592. }
  67593. }
  67594. if (this._filter === value) {
  67595. return;
  67596. }
  67597. this._filter = value;
  67598. this._disposeBlurPostProcesses();
  67599. this._applyFilterValues();
  67600. this._light._markMeshesAsLightDirty();
  67601. },
  67602. enumerable: true,
  67603. configurable: true
  67604. });
  67605. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  67606. /**
  67607. * Gets if the current filter is set to Poisson Sampling.
  67608. */
  67609. get: function () {
  67610. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  67611. },
  67612. /**
  67613. * Sets the current filter to Poisson Sampling.
  67614. */
  67615. set: function (value) {
  67616. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  67617. return;
  67618. }
  67619. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  67620. },
  67621. enumerable: true,
  67622. configurable: true
  67623. });
  67624. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  67625. /**
  67626. * Gets if the current filter is set to VSM.
  67627. * DEPRECATED. Should use useExponentialShadowMap instead.
  67628. */
  67629. get: function () {
  67630. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67631. return this.useExponentialShadowMap;
  67632. },
  67633. /**
  67634. * Sets the current filter is to VSM.
  67635. * DEPRECATED. Should use useExponentialShadowMap instead.
  67636. */
  67637. set: function (value) {
  67638. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67639. this.useExponentialShadowMap = value;
  67640. },
  67641. enumerable: true,
  67642. configurable: true
  67643. });
  67644. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  67645. /**
  67646. * Gets if the current filter is set to blurred VSM.
  67647. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67648. */
  67649. get: function () {
  67650. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67651. return this.useBlurExponentialShadowMap;
  67652. },
  67653. /**
  67654. * Sets the current filter is to blurred VSM.
  67655. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67656. */
  67657. set: function (value) {
  67658. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67659. this.useBlurExponentialShadowMap = value;
  67660. },
  67661. enumerable: true,
  67662. configurable: true
  67663. });
  67664. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  67665. /**
  67666. * Gets if the current filter is set to ESM.
  67667. */
  67668. get: function () {
  67669. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  67670. },
  67671. /**
  67672. * Sets the current filter is to ESM.
  67673. */
  67674. set: function (value) {
  67675. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  67676. return;
  67677. }
  67678. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67679. },
  67680. enumerable: true,
  67681. configurable: true
  67682. });
  67683. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  67684. /**
  67685. * Gets if the current filter is set to filtered ESM.
  67686. */
  67687. get: function () {
  67688. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  67689. },
  67690. /**
  67691. * Gets if the current filter is set to filtered ESM.
  67692. */
  67693. set: function (value) {
  67694. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67695. return;
  67696. }
  67697. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67698. },
  67699. enumerable: true,
  67700. configurable: true
  67701. });
  67702. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  67703. /**
  67704. * Gets if the current filter is set to "close ESM" (using the inverse of the
  67705. * exponential to prevent steep falloff artifacts).
  67706. */
  67707. get: function () {
  67708. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  67709. },
  67710. /**
  67711. * Sets the current filter to "close ESM" (using the inverse of the
  67712. * exponential to prevent steep falloff artifacts).
  67713. */
  67714. set: function (value) {
  67715. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  67716. return;
  67717. }
  67718. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67719. },
  67720. enumerable: true,
  67721. configurable: true
  67722. });
  67723. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  67724. /**
  67725. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  67726. * exponential to prevent steep falloff artifacts).
  67727. */
  67728. get: function () {
  67729. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  67730. },
  67731. /**
  67732. * Sets the current filter to filtered "close ESM" (using the inverse of the
  67733. * exponential to prevent steep falloff artifacts).
  67734. */
  67735. set: function (value) {
  67736. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67737. return;
  67738. }
  67739. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67740. },
  67741. enumerable: true,
  67742. configurable: true
  67743. });
  67744. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  67745. /**
  67746. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  67747. */
  67748. get: function () {
  67749. return this.filter === ShadowGenerator.FILTER_PCF;
  67750. },
  67751. /**
  67752. * Sets the current filter to "PCF" (percentage closer filtering).
  67753. */
  67754. set: function (value) {
  67755. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  67756. return;
  67757. }
  67758. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  67759. },
  67760. enumerable: true,
  67761. configurable: true
  67762. });
  67763. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  67764. /**
  67765. * Gets the PCF or PCSS Quality.
  67766. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67767. */
  67768. get: function () {
  67769. return this._filteringQuality;
  67770. },
  67771. /**
  67772. * Sets the PCF or PCSS Quality.
  67773. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67774. */
  67775. set: function (filteringQuality) {
  67776. this._filteringQuality = filteringQuality;
  67777. },
  67778. enumerable: true,
  67779. configurable: true
  67780. });
  67781. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  67782. /**
  67783. * Gets if the current filter is set to "PCSS" (contact hardening).
  67784. */
  67785. get: function () {
  67786. return this.filter === ShadowGenerator.FILTER_PCSS;
  67787. },
  67788. /**
  67789. * Sets the current filter to "PCSS" (contact hardening).
  67790. */
  67791. set: function (value) {
  67792. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  67793. return;
  67794. }
  67795. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  67796. },
  67797. enumerable: true,
  67798. configurable: true
  67799. });
  67800. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  67801. /**
  67802. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67803. * Using a ratio helps keeping shape stability independently of the map size.
  67804. *
  67805. * It does not account for the light projection as it was having too much
  67806. * instability during the light setup or during light position changes.
  67807. *
  67808. * Only valid if useContactHardeningShadow is true.
  67809. */
  67810. get: function () {
  67811. return this._contactHardeningLightSizeUVRatio;
  67812. },
  67813. /**
  67814. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67815. * Using a ratio helps keeping shape stability independently of the map size.
  67816. *
  67817. * It does not account for the light projection as it was having too much
  67818. * instability during the light setup or during light position changes.
  67819. *
  67820. * Only valid if useContactHardeningShadow is true.
  67821. */
  67822. set: function (contactHardeningLightSizeUVRatio) {
  67823. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  67824. },
  67825. enumerable: true,
  67826. configurable: true
  67827. });
  67828. /**
  67829. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  67830. * 0 means strongest and 1 would means no shadow.
  67831. * @returns the darkness.
  67832. */
  67833. ShadowGenerator.prototype.getDarkness = function () {
  67834. return this._darkness;
  67835. };
  67836. /**
  67837. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  67838. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  67839. * @returns the shadow generator allowing fluent coding.
  67840. */
  67841. ShadowGenerator.prototype.setDarkness = function (darkness) {
  67842. if (darkness >= 1.0)
  67843. this._darkness = 1.0;
  67844. else if (darkness <= 0.0)
  67845. this._darkness = 0.0;
  67846. else
  67847. this._darkness = darkness;
  67848. return this;
  67849. };
  67850. /**
  67851. * Sets the ability to have transparent shadow (boolean).
  67852. * @param transparent True if transparent else False
  67853. * @returns the shadow generator allowing fluent coding
  67854. */
  67855. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  67856. this._transparencyShadow = transparent;
  67857. return this;
  67858. };
  67859. /**
  67860. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  67861. * @returns The render target texture if present otherwise, null
  67862. */
  67863. ShadowGenerator.prototype.getShadowMap = function () {
  67864. return this._shadowMap;
  67865. };
  67866. /**
  67867. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  67868. * @returns The render target texture if the shadow map is present otherwise, null
  67869. */
  67870. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  67871. if (this._shadowMap2) {
  67872. return this._shadowMap2;
  67873. }
  67874. return this._shadowMap;
  67875. };
  67876. /**
  67877. * Helper function to add a mesh and its descendants to the list of shadow casters.
  67878. * @param mesh Mesh to add
  67879. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  67880. * @returns the Shadow Generator itself
  67881. */
  67882. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  67883. if (includeDescendants === void 0) { includeDescendants = true; }
  67884. if (!this._shadowMap) {
  67885. return this;
  67886. }
  67887. if (!this._shadowMap.renderList) {
  67888. this._shadowMap.renderList = [];
  67889. }
  67890. this._shadowMap.renderList.push(mesh);
  67891. if (includeDescendants) {
  67892. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  67893. }
  67894. return this;
  67895. var _a;
  67896. };
  67897. /**
  67898. * Helper function to remove a mesh and its descendants from the list of shadow casters
  67899. * @param mesh Mesh to remove
  67900. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  67901. * @returns the Shadow Generator itself
  67902. */
  67903. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  67904. if (includeDescendants === void 0) { includeDescendants = true; }
  67905. if (!this._shadowMap || !this._shadowMap.renderList) {
  67906. return this;
  67907. }
  67908. var index = this._shadowMap.renderList.indexOf(mesh);
  67909. if (index !== -1) {
  67910. this._shadowMap.renderList.splice(index, 1);
  67911. }
  67912. if (includeDescendants) {
  67913. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  67914. var child = _a[_i];
  67915. this.removeShadowCaster(child);
  67916. }
  67917. }
  67918. return this;
  67919. };
  67920. /**
  67921. * Returns the associated light object.
  67922. * @returns the light generating the shadow
  67923. */
  67924. ShadowGenerator.prototype.getLight = function () {
  67925. return this._light;
  67926. };
  67927. ShadowGenerator.prototype._initializeGenerator = function () {
  67928. this._light._markMeshesAsLightDirty();
  67929. this._initializeShadowMap();
  67930. };
  67931. ShadowGenerator.prototype._initializeShadowMap = function () {
  67932. var _this = this;
  67933. // Render target
  67934. var engine = this._scene.getEngine();
  67935. if (engine.webGLVersion > 1) {
  67936. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  67937. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  67938. }
  67939. else {
  67940. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  67941. }
  67942. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67943. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67944. this._shadowMap.anisotropicFilteringLevel = 1;
  67945. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67946. this._shadowMap.renderParticles = false;
  67947. this._shadowMap.ignoreCameraViewport = true;
  67948. // Record Face Index before render.
  67949. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  67950. _this._currentFaceIndex = faceIndex;
  67951. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67952. engine.setColorWrite(false);
  67953. }
  67954. });
  67955. // Custom render function.
  67956. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  67957. // Blur if required afer render.
  67958. this._shadowMap.onAfterUnbindObservable.add(function () {
  67959. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67960. engine.setColorWrite(true);
  67961. }
  67962. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  67963. return;
  67964. }
  67965. var shadowMap = _this.getShadowMapForRendering();
  67966. if (shadowMap) {
  67967. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  67968. }
  67969. });
  67970. // Clear according to the chosen filter.
  67971. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  67972. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67973. this._shadowMap.onClearObservable.add(function (engine) {
  67974. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67975. engine.clear(clearOne, false, true, false);
  67976. }
  67977. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  67978. engine.clear(clearZero, true, true, false);
  67979. }
  67980. else {
  67981. engine.clear(clearOne, true, true, false);
  67982. }
  67983. });
  67984. };
  67985. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  67986. var _this = this;
  67987. var engine = this._scene.getEngine();
  67988. var targetSize = this._mapSize / this.blurScale;
  67989. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  67990. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  67991. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67992. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67993. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67994. }
  67995. if (this.useKernelBlur) {
  67996. 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);
  67997. this._kernelBlurXPostprocess.width = targetSize;
  67998. this._kernelBlurXPostprocess.height = targetSize;
  67999. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  68000. effect.setTexture("textureSampler", _this._shadowMap);
  68001. });
  68002. 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);
  68003. this._kernelBlurXPostprocess.autoClear = false;
  68004. this._kernelBlurYPostprocess.autoClear = false;
  68005. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68006. this._kernelBlurXPostprocess.packedFloat = true;
  68007. this._kernelBlurYPostprocess.packedFloat = true;
  68008. }
  68009. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  68010. }
  68011. else {
  68012. 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);
  68013. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  68014. effect.setFloat2("screenSize", targetSize, targetSize);
  68015. effect.setTexture("textureSampler", _this._shadowMap);
  68016. });
  68017. this._boxBlurPostprocess.autoClear = false;
  68018. this._blurPostProcesses = [this._boxBlurPostprocess];
  68019. }
  68020. };
  68021. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68022. var index;
  68023. var engine = this._scene.getEngine();
  68024. if (depthOnlySubMeshes.length) {
  68025. engine.setColorWrite(false);
  68026. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68027. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  68028. }
  68029. engine.setColorWrite(true);
  68030. }
  68031. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68032. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  68033. }
  68034. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68035. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  68036. }
  68037. if (this._transparencyShadow) {
  68038. for (index = 0; index < transparentSubMeshes.length; index++) {
  68039. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  68040. }
  68041. }
  68042. };
  68043. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  68044. var _this = this;
  68045. var mesh = subMesh.getRenderingMesh();
  68046. var scene = this._scene;
  68047. var engine = scene.getEngine();
  68048. var material = subMesh.getMaterial();
  68049. if (!material) {
  68050. return;
  68051. }
  68052. // Culling
  68053. engine.setState(material.backFaceCulling);
  68054. // Managing instances
  68055. var batch = mesh._getInstancesRenderList(subMesh._id);
  68056. if (batch.mustReturn) {
  68057. return;
  68058. }
  68059. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68060. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  68061. engine.enableEffect(this._effect);
  68062. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68063. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  68064. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  68065. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68066. this._effect.setVector3("lightData", this._cachedDirection);
  68067. }
  68068. else {
  68069. this._effect.setVector3("lightData", this._cachedPosition);
  68070. }
  68071. if (scene.activeCamera) {
  68072. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  68073. }
  68074. // Alpha test
  68075. if (material && material.needAlphaTesting()) {
  68076. var alphaTexture = material.getAlphaTestTexture();
  68077. if (alphaTexture) {
  68078. this._effect.setTexture("diffuseSampler", alphaTexture);
  68079. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  68080. }
  68081. }
  68082. // Bones
  68083. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68084. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  68085. }
  68086. // Morph targets
  68087. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  68088. if (this.forceBackFacesOnly) {
  68089. engine.setState(true, 0, false, true);
  68090. }
  68091. // Draw
  68092. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68093. if (this.forceBackFacesOnly) {
  68094. engine.setState(true, 0, false, false);
  68095. }
  68096. }
  68097. else {
  68098. // Need to reset refresh rate of the shadowMap
  68099. if (this._shadowMap) {
  68100. this._shadowMap.resetRefreshCounter();
  68101. }
  68102. }
  68103. };
  68104. ShadowGenerator.prototype._applyFilterValues = function () {
  68105. if (!this._shadowMap) {
  68106. return;
  68107. }
  68108. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  68109. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68110. }
  68111. else {
  68112. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68113. }
  68114. };
  68115. /**
  68116. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68117. * @param onCompiled Callback triggered at the and of the effects compilation
  68118. * @param options Sets of optional options forcing the compilation with different modes
  68119. */
  68120. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  68121. var _this = this;
  68122. var localOptions = __assign({ useInstances: false }, options);
  68123. var shadowMap = this.getShadowMap();
  68124. if (!shadowMap) {
  68125. if (onCompiled) {
  68126. onCompiled(this);
  68127. }
  68128. return;
  68129. }
  68130. var renderList = shadowMap.renderList;
  68131. if (!renderList) {
  68132. if (onCompiled) {
  68133. onCompiled(this);
  68134. }
  68135. return;
  68136. }
  68137. var subMeshes = new Array();
  68138. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  68139. var mesh = renderList_1[_i];
  68140. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  68141. }
  68142. if (subMeshes.length === 0) {
  68143. if (onCompiled) {
  68144. onCompiled(this);
  68145. }
  68146. return;
  68147. }
  68148. var currentIndex = 0;
  68149. var checkReady = function () {
  68150. if (!_this._scene || !_this._scene.getEngine()) {
  68151. return;
  68152. }
  68153. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  68154. currentIndex++;
  68155. if (currentIndex >= subMeshes.length) {
  68156. if (onCompiled) {
  68157. onCompiled(_this);
  68158. }
  68159. return;
  68160. }
  68161. }
  68162. setTimeout(checkReady, 16);
  68163. };
  68164. checkReady();
  68165. };
  68166. /**
  68167. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68168. * @param options Sets of optional options forcing the compilation with different modes
  68169. * @returns A promise that resolves when the compilation completes
  68170. */
  68171. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  68172. var _this = this;
  68173. return new Promise(function (resolve) {
  68174. _this.forceCompilation(function () {
  68175. resolve();
  68176. }, options);
  68177. });
  68178. };
  68179. /**
  68180. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  68181. * @param subMesh The submesh we want to render in the shadow map
  68182. * @param useInstances Defines wether will draw in the map using instances
  68183. * @returns true if ready otherwise, false
  68184. */
  68185. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  68186. var defines = [];
  68187. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68188. defines.push("#define FLOAT");
  68189. }
  68190. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68191. defines.push("#define ESM");
  68192. }
  68193. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  68194. defines.push("#define DEPTHTEXTURE");
  68195. }
  68196. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68197. var mesh = subMesh.getMesh();
  68198. var material = subMesh.getMaterial();
  68199. // Normal bias.
  68200. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68201. attribs.push(BABYLON.VertexBuffer.NormalKind);
  68202. defines.push("#define NORMAL");
  68203. if (mesh.nonUniformScaling) {
  68204. defines.push("#define NONUNIFORMSCALING");
  68205. }
  68206. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68207. defines.push("#define DIRECTIONINLIGHTDATA");
  68208. }
  68209. }
  68210. // Alpha test
  68211. if (material && material.needAlphaTesting()) {
  68212. var alphaTexture = material.getAlphaTestTexture();
  68213. if (alphaTexture) {
  68214. defines.push("#define ALPHATEST");
  68215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68216. attribs.push(BABYLON.VertexBuffer.UVKind);
  68217. defines.push("#define UV1");
  68218. }
  68219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68220. if (alphaTexture.coordinatesIndex === 1) {
  68221. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68222. defines.push("#define UV2");
  68223. }
  68224. }
  68225. }
  68226. }
  68227. // Bones
  68228. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68229. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68230. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68231. if (mesh.numBoneInfluencers > 4) {
  68232. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68233. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68234. }
  68235. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68236. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68237. }
  68238. else {
  68239. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68240. }
  68241. // Morph targets
  68242. var manager = mesh.morphTargetManager;
  68243. var morphInfluencers = 0;
  68244. if (manager) {
  68245. if (manager.numInfluencers > 0) {
  68246. defines.push("#define MORPHTARGETS");
  68247. morphInfluencers = manager.numInfluencers;
  68248. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  68249. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  68250. }
  68251. }
  68252. // Instances
  68253. if (useInstances) {
  68254. defines.push("#define INSTANCES");
  68255. attribs.push("world0");
  68256. attribs.push("world1");
  68257. attribs.push("world2");
  68258. attribs.push("world3");
  68259. }
  68260. // Get correct effect
  68261. var join = defines.join("\n");
  68262. if (this._cachedDefines !== join) {
  68263. this._cachedDefines = join;
  68264. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  68265. }
  68266. if (!this._effect.isReady()) {
  68267. return false;
  68268. }
  68269. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68270. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  68271. this._initializeBlurRTTAndPostProcesses();
  68272. }
  68273. }
  68274. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  68275. return false;
  68276. }
  68277. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  68278. return false;
  68279. }
  68280. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  68281. return false;
  68282. }
  68283. return true;
  68284. };
  68285. /**
  68286. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  68287. * @param defines Defines of the material we want to update
  68288. * @param lightIndex Index of the light in the enabled light list of the material
  68289. */
  68290. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  68291. var scene = this._scene;
  68292. var light = this._light;
  68293. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68294. return;
  68295. }
  68296. defines["SHADOW" + lightIndex] = true;
  68297. if (this.useContactHardeningShadow) {
  68298. defines["SHADOWPCSS" + lightIndex] = true;
  68299. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68300. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68301. }
  68302. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68303. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68304. }
  68305. // else default to high.
  68306. }
  68307. if (this.usePercentageCloserFiltering) {
  68308. defines["SHADOWPCF" + lightIndex] = true;
  68309. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68310. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68311. }
  68312. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68313. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68314. }
  68315. // else default to high.
  68316. }
  68317. else if (this.usePoissonSampling) {
  68318. defines["SHADOWPOISSON" + lightIndex] = true;
  68319. }
  68320. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68321. defines["SHADOWESM" + lightIndex] = true;
  68322. }
  68323. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68324. defines["SHADOWCLOSEESM" + lightIndex] = true;
  68325. }
  68326. if (light.needCube()) {
  68327. defines["SHADOWCUBE" + lightIndex] = true;
  68328. }
  68329. };
  68330. /**
  68331. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  68332. * defined in the generator but impacting the effect).
  68333. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  68334. * @param effect The effect we are binfing the information for
  68335. */
  68336. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  68337. var light = this._light;
  68338. var scene = this._scene;
  68339. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68340. return;
  68341. }
  68342. var camera = scene.activeCamera;
  68343. if (!camera) {
  68344. return;
  68345. }
  68346. var shadowMap = this.getShadowMap();
  68347. if (!shadowMap) {
  68348. return;
  68349. }
  68350. if (!light.needCube()) {
  68351. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  68352. }
  68353. // Only PCF uses depth stencil texture.
  68354. if (this._filter === ShadowGenerator.FILTER_PCF) {
  68355. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68356. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68357. }
  68358. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  68359. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68360. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  68361. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68362. }
  68363. else {
  68364. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68365. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  68366. }
  68367. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  68368. };
  68369. /**
  68370. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  68371. * (eq to shadow prjection matrix * light transform matrix)
  68372. * @returns The transform matrix used to create the shadow map
  68373. */
  68374. ShadowGenerator.prototype.getTransformMatrix = function () {
  68375. var scene = this._scene;
  68376. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  68377. return this._transformMatrix;
  68378. }
  68379. this._currentRenderID = scene.getRenderId();
  68380. this._currentFaceIndexCache = this._currentFaceIndex;
  68381. var lightPosition = this._light.position;
  68382. if (this._light.computeTransformedInformation()) {
  68383. lightPosition = this._light.transformedPosition;
  68384. }
  68385. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  68386. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  68387. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  68388. }
  68389. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  68390. this._cachedPosition.copyFrom(lightPosition);
  68391. this._cachedDirection.copyFrom(this._lightDirection);
  68392. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  68393. var shadowMap = this.getShadowMap();
  68394. if (shadowMap) {
  68395. var renderList = shadowMap.renderList;
  68396. if (renderList) {
  68397. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  68398. }
  68399. }
  68400. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  68401. }
  68402. return this._transformMatrix;
  68403. };
  68404. /**
  68405. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  68406. * Cube and 2D textures for instance.
  68407. */
  68408. ShadowGenerator.prototype.recreateShadowMap = function () {
  68409. var shadowMap = this._shadowMap;
  68410. if (!shadowMap) {
  68411. return;
  68412. }
  68413. // Track render list.
  68414. var renderList = shadowMap.renderList;
  68415. // Clean up existing data.
  68416. this._disposeRTTandPostProcesses();
  68417. // Reinitializes.
  68418. this._initializeGenerator();
  68419. // Reaffect the filter to ensure a correct fallback if necessary.
  68420. this.filter = this.filter;
  68421. // Reaffect the filter.
  68422. this._applyFilterValues();
  68423. // Reaffect Render List.
  68424. this._shadowMap.renderList = renderList;
  68425. };
  68426. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  68427. if (this._shadowMap2) {
  68428. this._shadowMap2.dispose();
  68429. this._shadowMap2 = null;
  68430. }
  68431. if (this._boxBlurPostprocess) {
  68432. this._boxBlurPostprocess.dispose();
  68433. this._boxBlurPostprocess = null;
  68434. }
  68435. if (this._kernelBlurXPostprocess) {
  68436. this._kernelBlurXPostprocess.dispose();
  68437. this._kernelBlurXPostprocess = null;
  68438. }
  68439. if (this._kernelBlurYPostprocess) {
  68440. this._kernelBlurYPostprocess.dispose();
  68441. this._kernelBlurYPostprocess = null;
  68442. }
  68443. this._blurPostProcesses = [];
  68444. };
  68445. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  68446. if (this._shadowMap) {
  68447. this._shadowMap.dispose();
  68448. this._shadowMap = null;
  68449. }
  68450. this._disposeBlurPostProcesses();
  68451. };
  68452. /**
  68453. * Disposes the ShadowGenerator.
  68454. * Returns nothing.
  68455. */
  68456. ShadowGenerator.prototype.dispose = function () {
  68457. this._disposeRTTandPostProcesses();
  68458. if (this._light) {
  68459. this._light._shadowGenerator = null;
  68460. this._light._markMeshesAsLightDirty();
  68461. }
  68462. };
  68463. /**
  68464. * Serializes the shadow generator setup to a json object.
  68465. * @returns The serialized JSON object
  68466. */
  68467. ShadowGenerator.prototype.serialize = function () {
  68468. var serializationObject = {};
  68469. var shadowMap = this.getShadowMap();
  68470. if (!shadowMap) {
  68471. return serializationObject;
  68472. }
  68473. serializationObject.lightId = this._light.id;
  68474. serializationObject.mapSize = shadowMap.getRenderSize();
  68475. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  68476. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  68477. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68478. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68479. serializationObject.usePoissonSampling = this.usePoissonSampling;
  68480. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  68481. serializationObject.depthScale = this.depthScale;
  68482. serializationObject.darkness = this.getDarkness();
  68483. serializationObject.blurBoxOffset = this.blurBoxOffset;
  68484. serializationObject.blurKernel = this.blurKernel;
  68485. serializationObject.blurScale = this.blurScale;
  68486. serializationObject.useKernelBlur = this.useKernelBlur;
  68487. serializationObject.transparencyShadow = this._transparencyShadow;
  68488. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  68489. serializationObject.bias = this.bias;
  68490. serializationObject.normalBias = this.normalBias;
  68491. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  68492. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  68493. serializationObject.filteringQuality = this.filteringQuality;
  68494. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  68495. serializationObject.renderList = [];
  68496. if (shadowMap.renderList) {
  68497. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  68498. var mesh = shadowMap.renderList[meshIndex];
  68499. serializationObject.renderList.push(mesh.id);
  68500. }
  68501. }
  68502. return serializationObject;
  68503. };
  68504. /**
  68505. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  68506. * @param parsedShadowGenerator The JSON object to parse
  68507. * @param scene The scene to create the shadow map for
  68508. * @returns The parsed shadow generator
  68509. */
  68510. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  68511. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  68512. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  68513. var shadowMap = shadowGenerator.getShadowMap();
  68514. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  68515. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  68516. meshes.forEach(function (mesh) {
  68517. if (!shadowMap) {
  68518. return;
  68519. }
  68520. if (!shadowMap.renderList) {
  68521. shadowMap.renderList = [];
  68522. }
  68523. shadowMap.renderList.push(mesh);
  68524. });
  68525. }
  68526. if (parsedShadowGenerator.usePoissonSampling) {
  68527. shadowGenerator.usePoissonSampling = true;
  68528. }
  68529. else if (parsedShadowGenerator.useExponentialShadowMap) {
  68530. shadowGenerator.useExponentialShadowMap = true;
  68531. }
  68532. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  68533. shadowGenerator.useBlurExponentialShadowMap = true;
  68534. }
  68535. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  68536. shadowGenerator.useCloseExponentialShadowMap = true;
  68537. }
  68538. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  68539. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  68540. }
  68541. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  68542. shadowGenerator.usePercentageCloserFiltering = true;
  68543. }
  68544. else if (parsedShadowGenerator.useContactHardeningShadow) {
  68545. shadowGenerator.useContactHardeningShadow = true;
  68546. }
  68547. if (parsedShadowGenerator.filteringQuality) {
  68548. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  68549. }
  68550. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  68551. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  68552. }
  68553. // Backward compat
  68554. else if (parsedShadowGenerator.useVarianceShadowMap) {
  68555. shadowGenerator.useExponentialShadowMap = true;
  68556. }
  68557. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  68558. shadowGenerator.useBlurExponentialShadowMap = true;
  68559. }
  68560. if (parsedShadowGenerator.depthScale) {
  68561. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  68562. }
  68563. if (parsedShadowGenerator.blurScale) {
  68564. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  68565. }
  68566. if (parsedShadowGenerator.blurBoxOffset) {
  68567. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  68568. }
  68569. if (parsedShadowGenerator.useKernelBlur) {
  68570. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  68571. }
  68572. if (parsedShadowGenerator.blurKernel) {
  68573. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  68574. }
  68575. if (parsedShadowGenerator.bias !== undefined) {
  68576. shadowGenerator.bias = parsedShadowGenerator.bias;
  68577. }
  68578. if (parsedShadowGenerator.normalBias !== undefined) {
  68579. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  68580. }
  68581. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  68582. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  68583. }
  68584. if (parsedShadowGenerator.darkness) {
  68585. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  68586. }
  68587. if (parsedShadowGenerator.transparencyShadow) {
  68588. shadowGenerator.setTransparencyShadow(true);
  68589. }
  68590. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  68591. return shadowGenerator;
  68592. };
  68593. /**
  68594. * Shadow generator mode None: no filtering applied.
  68595. */
  68596. ShadowGenerator.FILTER_NONE = 0;
  68597. /**
  68598. * Shadow generator mode ESM: Exponential Shadow Mapping.
  68599. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68600. */
  68601. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  68602. /**
  68603. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  68604. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  68605. */
  68606. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  68607. /**
  68608. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  68609. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68610. */
  68611. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  68612. /**
  68613. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  68614. * edge artifacts on steep falloff.
  68615. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68616. */
  68617. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  68618. /**
  68619. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  68620. * edge artifacts on steep falloff.
  68621. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68622. */
  68623. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  68624. /**
  68625. * Shadow generator mode PCF: Percentage Closer Filtering
  68626. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68627. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  68628. */
  68629. ShadowGenerator.FILTER_PCF = 6;
  68630. /**
  68631. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  68632. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68633. * Contact Hardening
  68634. */
  68635. ShadowGenerator.FILTER_PCSS = 7;
  68636. /**
  68637. * Reserved for PCF and PCSS
  68638. * Highest Quality.
  68639. *
  68640. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  68641. *
  68642. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  68643. */
  68644. ShadowGenerator.QUALITY_HIGH = 0;
  68645. /**
  68646. * Reserved for PCF and PCSS
  68647. * Good tradeoff for quality/perf cross devices
  68648. *
  68649. * Execute PCF on a 3*3 kernel.
  68650. *
  68651. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  68652. */
  68653. ShadowGenerator.QUALITY_MEDIUM = 1;
  68654. /**
  68655. * Reserved for PCF and PCSS
  68656. * The lowest quality but the fastest.
  68657. *
  68658. * Execute PCF on a 1*1 kernel.
  68659. *
  68660. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  68661. */
  68662. ShadowGenerator.QUALITY_LOW = 2;
  68663. return ShadowGenerator;
  68664. }());
  68665. BABYLON.ShadowGenerator = ShadowGenerator;
  68666. })(BABYLON || (BABYLON = {}));
  68667. //# sourceMappingURL=babylon.shadowGenerator.js.map
  68668. var BABYLON;
  68669. (function (BABYLON) {
  68670. var DefaultLoadingScreen = /** @class */ (function () {
  68671. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  68672. if (_loadingText === void 0) { _loadingText = ""; }
  68673. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  68674. var _this = this;
  68675. this._renderingCanvas = _renderingCanvas;
  68676. this._loadingText = _loadingText;
  68677. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  68678. // Resize
  68679. this._resizeLoadingUI = function () {
  68680. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  68681. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  68682. if (!_this._loadingDiv) {
  68683. return;
  68684. }
  68685. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  68686. _this._loadingDiv.style.left = canvasRect.left + "px";
  68687. _this._loadingDiv.style.top = canvasRect.top + "px";
  68688. _this._loadingDiv.style.width = canvasRect.width + "px";
  68689. _this._loadingDiv.style.height = canvasRect.height + "px";
  68690. };
  68691. }
  68692. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  68693. if (this._loadingDiv) {
  68694. // Do not add a loading screen if there is already one
  68695. return;
  68696. }
  68697. this._loadingDiv = document.createElement("div");
  68698. this._loadingDiv.id = "babylonjsLoadingDiv";
  68699. this._loadingDiv.style.opacity = "0";
  68700. this._loadingDiv.style.transition = "opacity 1.5s ease";
  68701. this._loadingDiv.style.pointerEvents = "none";
  68702. // Loading text
  68703. this._loadingTextDiv = document.createElement("div");
  68704. this._loadingTextDiv.style.position = "absolute";
  68705. this._loadingTextDiv.style.left = "0";
  68706. this._loadingTextDiv.style.top = "50%";
  68707. this._loadingTextDiv.style.marginTop = "80px";
  68708. this._loadingTextDiv.style.width = "100%";
  68709. this._loadingTextDiv.style.height = "20px";
  68710. this._loadingTextDiv.style.fontFamily = "Arial";
  68711. this._loadingTextDiv.style.fontSize = "14px";
  68712. this._loadingTextDiv.style.color = "white";
  68713. this._loadingTextDiv.style.textAlign = "center";
  68714. this._loadingTextDiv.innerHTML = "Loading";
  68715. this._loadingDiv.appendChild(this._loadingTextDiv);
  68716. //set the predefined text
  68717. this._loadingTextDiv.innerHTML = this._loadingText;
  68718. // Generating keyframes
  68719. var style = document.createElement('style');
  68720. style.type = 'text/css';
  68721. 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 }";
  68722. style.innerHTML = keyFrames;
  68723. document.getElementsByTagName('head')[0].appendChild(style);
  68724. // Loading img
  68725. var imgBack = new Image();
  68726. 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";
  68727. imgBack.style.position = "absolute";
  68728. imgBack.style.left = "50%";
  68729. imgBack.style.top = "50%";
  68730. imgBack.style.marginLeft = "-60px";
  68731. imgBack.style.marginTop = "-60px";
  68732. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  68733. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  68734. imgBack.style.transformOrigin = "50% 50%";
  68735. imgBack.style.webkitTransformOrigin = "50% 50%";
  68736. this._loadingDiv.appendChild(imgBack);
  68737. this._resizeLoadingUI();
  68738. window.addEventListener("resize", this._resizeLoadingUI);
  68739. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68740. document.body.appendChild(this._loadingDiv);
  68741. this._loadingDiv.style.opacity = "1";
  68742. };
  68743. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  68744. var _this = this;
  68745. if (!this._loadingDiv) {
  68746. return;
  68747. }
  68748. var onTransitionEnd = function () {
  68749. if (!_this._loadingDiv) {
  68750. return;
  68751. }
  68752. document.body.removeChild(_this._loadingDiv);
  68753. window.removeEventListener("resize", _this._resizeLoadingUI);
  68754. _this._loadingDiv = null;
  68755. };
  68756. this._loadingDiv.style.opacity = "0";
  68757. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  68758. };
  68759. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  68760. set: function (text) {
  68761. this._loadingText = text;
  68762. if (this._loadingTextDiv) {
  68763. this._loadingTextDiv.innerHTML = this._loadingText;
  68764. }
  68765. },
  68766. enumerable: true,
  68767. configurable: true
  68768. });
  68769. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  68770. get: function () {
  68771. return this._loadingDivBackgroundColor;
  68772. },
  68773. set: function (color) {
  68774. this._loadingDivBackgroundColor = color;
  68775. if (!this._loadingDiv) {
  68776. return;
  68777. }
  68778. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68779. },
  68780. enumerable: true,
  68781. configurable: true
  68782. });
  68783. return DefaultLoadingScreen;
  68784. }());
  68785. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  68786. })(BABYLON || (BABYLON = {}));
  68787. //# sourceMappingURL=babylon.loadingScreen.js.map
  68788. var BABYLON;
  68789. (function (BABYLON) {
  68790. var SceneLoaderProgressEvent = /** @class */ (function () {
  68791. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  68792. this.lengthComputable = lengthComputable;
  68793. this.loaded = loaded;
  68794. this.total = total;
  68795. }
  68796. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  68797. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  68798. };
  68799. return SceneLoaderProgressEvent;
  68800. }());
  68801. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  68802. var SceneLoader = /** @class */ (function () {
  68803. function SceneLoader() {
  68804. }
  68805. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  68806. get: function () {
  68807. return 0;
  68808. },
  68809. enumerable: true,
  68810. configurable: true
  68811. });
  68812. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  68813. get: function () {
  68814. return 1;
  68815. },
  68816. enumerable: true,
  68817. configurable: true
  68818. });
  68819. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  68820. get: function () {
  68821. return 2;
  68822. },
  68823. enumerable: true,
  68824. configurable: true
  68825. });
  68826. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  68827. get: function () {
  68828. return 3;
  68829. },
  68830. enumerable: true,
  68831. configurable: true
  68832. });
  68833. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  68834. get: function () {
  68835. return SceneLoader._ForceFullSceneLoadingForIncremental;
  68836. },
  68837. set: function (value) {
  68838. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  68839. },
  68840. enumerable: true,
  68841. configurable: true
  68842. });
  68843. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  68844. get: function () {
  68845. return SceneLoader._ShowLoadingScreen;
  68846. },
  68847. set: function (value) {
  68848. SceneLoader._ShowLoadingScreen = value;
  68849. },
  68850. enumerable: true,
  68851. configurable: true
  68852. });
  68853. Object.defineProperty(SceneLoader, "loggingLevel", {
  68854. get: function () {
  68855. return SceneLoader._loggingLevel;
  68856. },
  68857. set: function (value) {
  68858. SceneLoader._loggingLevel = value;
  68859. },
  68860. enumerable: true,
  68861. configurable: true
  68862. });
  68863. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  68864. get: function () {
  68865. return SceneLoader._CleanBoneMatrixWeights;
  68866. },
  68867. set: function (value) {
  68868. SceneLoader._CleanBoneMatrixWeights = value;
  68869. },
  68870. enumerable: true,
  68871. configurable: true
  68872. });
  68873. SceneLoader._getDefaultPlugin = function () {
  68874. return SceneLoader._registeredPlugins[".babylon"];
  68875. };
  68876. SceneLoader._getPluginForExtension = function (extension) {
  68877. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  68878. if (registeredPlugin) {
  68879. return registeredPlugin;
  68880. }
  68881. 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");
  68882. return SceneLoader._getDefaultPlugin();
  68883. };
  68884. SceneLoader._getPluginForDirectLoad = function (data) {
  68885. for (var extension in SceneLoader._registeredPlugins) {
  68886. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  68887. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  68888. return SceneLoader._registeredPlugins[extension];
  68889. }
  68890. }
  68891. return SceneLoader._getDefaultPlugin();
  68892. };
  68893. SceneLoader._getPluginForFilename = function (sceneFilename) {
  68894. if (sceneFilename.name) {
  68895. sceneFilename = sceneFilename.name;
  68896. }
  68897. var queryStringPosition = sceneFilename.indexOf("?");
  68898. if (queryStringPosition !== -1) {
  68899. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  68900. }
  68901. var dotPosition = sceneFilename.lastIndexOf(".");
  68902. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  68903. return SceneLoader._getPluginForExtension(extension);
  68904. };
  68905. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  68906. SceneLoader._getDirectLoad = function (sceneFilename) {
  68907. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  68908. return sceneFilename.substr(5);
  68909. }
  68910. return null;
  68911. };
  68912. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  68913. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  68914. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  68915. var plugin;
  68916. if (registeredPlugin.plugin.createPlugin) {
  68917. plugin = registeredPlugin.plugin.createPlugin();
  68918. }
  68919. else {
  68920. plugin = registeredPlugin.plugin;
  68921. }
  68922. var useArrayBuffer = registeredPlugin.isBinary;
  68923. var database;
  68924. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  68925. var dataCallback = function (data, responseURL) {
  68926. if (scene.isDisposed) {
  68927. onError("Scene has been disposed");
  68928. return;
  68929. }
  68930. scene.database = database;
  68931. onSuccess(plugin, data, responseURL);
  68932. };
  68933. var request = null;
  68934. var pluginDisposed = false;
  68935. var onDisposeObservable = plugin.onDisposeObservable;
  68936. if (onDisposeObservable) {
  68937. onDisposeObservable.add(function () {
  68938. pluginDisposed = true;
  68939. if (request) {
  68940. request.abort();
  68941. request = null;
  68942. }
  68943. onDispose();
  68944. });
  68945. }
  68946. var manifestChecked = function () {
  68947. if (pluginDisposed) {
  68948. return;
  68949. }
  68950. var url = rootUrl + sceneFilename;
  68951. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  68952. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  68953. } : undefined, database, useArrayBuffer, function (request, exception) {
  68954. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  68955. });
  68956. };
  68957. if (directLoad) {
  68958. dataCallback(directLoad);
  68959. return plugin;
  68960. }
  68961. if (rootUrl.indexOf("file:") === -1) {
  68962. var engine = scene.getEngine();
  68963. var canUseOfflineSupport = engine.enableOfflineSupport;
  68964. if (canUseOfflineSupport) {
  68965. // Also check for exceptions
  68966. var exceptionFound = false;
  68967. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  68968. var regex = _a[_i];
  68969. if (regex.test(rootUrl + sceneFilename)) {
  68970. exceptionFound = true;
  68971. break;
  68972. }
  68973. }
  68974. canUseOfflineSupport = !exceptionFound;
  68975. }
  68976. if (canUseOfflineSupport) {
  68977. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  68978. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  68979. }
  68980. else {
  68981. manifestChecked();
  68982. }
  68983. }
  68984. // Loading file from disk via input file or drag'n'drop
  68985. else {
  68986. var fileOrString = sceneFilename;
  68987. if (fileOrString.name) { // File
  68988. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  68989. }
  68990. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  68991. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  68992. }
  68993. else {
  68994. onError("Unable to find file named " + sceneFilename);
  68995. }
  68996. }
  68997. return plugin;
  68998. };
  68999. // Public functions
  69000. SceneLoader.GetPluginForExtension = function (extension) {
  69001. return SceneLoader._getPluginForExtension(extension).plugin;
  69002. };
  69003. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  69004. return !!SceneLoader._registeredPlugins[extension];
  69005. };
  69006. SceneLoader.RegisterPlugin = function (plugin) {
  69007. if (typeof plugin.extensions === "string") {
  69008. var extension = plugin.extensions;
  69009. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69010. plugin: plugin,
  69011. isBinary: false
  69012. };
  69013. }
  69014. else {
  69015. var extensions = plugin.extensions;
  69016. Object.keys(extensions).forEach(function (extension) {
  69017. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69018. plugin: plugin,
  69019. isBinary: extensions[extension].isBinary
  69020. };
  69021. });
  69022. }
  69023. };
  69024. /**
  69025. * Import meshes into a scene
  69026. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69027. * @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)
  69028. * @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)
  69029. * @param scene the instance of BABYLON.Scene to append to
  69030. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  69031. * @param onProgress a callback with a progress event for each file being loaded
  69032. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69033. * @param pluginExtension the extension used to determine the plugin
  69034. * @returns The loaded plugin
  69035. */
  69036. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69037. if (sceneFilename === void 0) { sceneFilename = ""; }
  69038. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69039. if (onSuccess === void 0) { onSuccess = null; }
  69040. if (onProgress === void 0) { onProgress = null; }
  69041. if (onError === void 0) { onError = null; }
  69042. if (pluginExtension === void 0) { pluginExtension = null; }
  69043. if (!scene) {
  69044. BABYLON.Tools.Error("No scene available to import mesh to");
  69045. return null;
  69046. }
  69047. if (!sceneFilename) {
  69048. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69049. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69050. }
  69051. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69052. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69053. return null;
  69054. }
  69055. var loadingToken = {};
  69056. scene._addPendingData(loadingToken);
  69057. var disposeHandler = function () {
  69058. scene._removePendingData(loadingToken);
  69059. };
  69060. var errorHandler = function (message, exception) {
  69061. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  69062. if (onError) {
  69063. onError(scene, errorMessage, exception);
  69064. }
  69065. else {
  69066. BABYLON.Tools.Error(errorMessage);
  69067. // should the exception be thrown?
  69068. }
  69069. disposeHandler();
  69070. };
  69071. var progressHandler = onProgress ? function (event) {
  69072. try {
  69073. onProgress(event);
  69074. }
  69075. catch (e) {
  69076. errorHandler("Error in onProgress callback", e);
  69077. }
  69078. } : undefined;
  69079. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  69080. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  69081. if (onSuccess) {
  69082. try {
  69083. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  69084. }
  69085. catch (e) {
  69086. errorHandler("Error in onSuccess callback", e);
  69087. }
  69088. }
  69089. scene._removePendingData(loadingToken);
  69090. };
  69091. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69092. if (plugin.rewriteRootURL) {
  69093. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  69094. }
  69095. if (sceneFilename === "") {
  69096. if (sceneFilename === "") {
  69097. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69098. }
  69099. }
  69100. if (plugin.importMesh) {
  69101. var syncedPlugin = plugin;
  69102. var meshes = new Array();
  69103. var particleSystems = new Array();
  69104. var skeletons = new Array();
  69105. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  69106. return;
  69107. }
  69108. scene.loadingPluginName = plugin.name;
  69109. successHandler(meshes, particleSystems, skeletons, []);
  69110. }
  69111. else {
  69112. var asyncedPlugin = plugin;
  69113. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  69114. scene.loadingPluginName = plugin.name;
  69115. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  69116. }).catch(function (error) {
  69117. errorHandler(error.message, error);
  69118. });
  69119. }
  69120. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69121. };
  69122. /**
  69123. * Import meshes into a scene
  69124. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69125. * @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)
  69126. * @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)
  69127. * @param scene the instance of BABYLON.Scene to append to
  69128. * @param onProgress a callback with a progress event for each file being loaded
  69129. * @param pluginExtension the extension used to determine the plugin
  69130. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  69131. */
  69132. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69133. if (sceneFilename === void 0) { sceneFilename = ""; }
  69134. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69135. if (onProgress === void 0) { onProgress = null; }
  69136. if (pluginExtension === void 0) { pluginExtension = null; }
  69137. return new Promise(function (resolve, reject) {
  69138. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  69139. resolve({
  69140. meshes: meshes,
  69141. particleSystems: particleSystems,
  69142. skeletons: skeletons,
  69143. animationGroups: animationGroups
  69144. });
  69145. }, onProgress, function (scene, message, exception) {
  69146. reject(exception || new Error(message));
  69147. }, pluginExtension);
  69148. });
  69149. };
  69150. /**
  69151. * Load a scene
  69152. * @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)
  69153. * @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)
  69154. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69155. * @param onSuccess a callback with the scene when import succeeds
  69156. * @param onProgress a callback with a progress event for each file being loaded
  69157. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69158. * @param pluginExtension the extension used to determine the plugin
  69159. * @returns The loaded plugin
  69160. */
  69161. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  69162. if (onSuccess === void 0) { onSuccess = null; }
  69163. if (onProgress === void 0) { onProgress = null; }
  69164. if (onError === void 0) { onError = null; }
  69165. if (pluginExtension === void 0) { pluginExtension = null; }
  69166. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  69167. };
  69168. /**
  69169. * Load a scene
  69170. * @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)
  69171. * @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)
  69172. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69173. * @param onProgress a callback with a progress event for each file being loaded
  69174. * @param pluginExtension the extension used to determine the plugin
  69175. * @returns The loaded scene
  69176. */
  69177. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  69178. if (onProgress === void 0) { onProgress = null; }
  69179. if (pluginExtension === void 0) { pluginExtension = null; }
  69180. return new Promise(function (resolve, reject) {
  69181. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  69182. resolve(scene);
  69183. }, onProgress, function (scene, message, exception) {
  69184. reject(exception || new Error(message));
  69185. }, pluginExtension);
  69186. });
  69187. };
  69188. /**
  69189. * Append a scene
  69190. * @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)
  69191. * @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)
  69192. * @param scene is the instance of BABYLON.Scene to append to
  69193. * @param onSuccess a callback with the scene when import succeeds
  69194. * @param onProgress a callback with a progress event for each file being loaded
  69195. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69196. * @param pluginExtension the extension used to determine the plugin
  69197. * @returns The loaded plugin
  69198. */
  69199. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69200. if (sceneFilename === void 0) { sceneFilename = ""; }
  69201. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69202. if (onSuccess === void 0) { onSuccess = null; }
  69203. if (onProgress === void 0) { onProgress = null; }
  69204. if (onError === void 0) { onError = null; }
  69205. if (pluginExtension === void 0) { pluginExtension = null; }
  69206. if (!scene) {
  69207. BABYLON.Tools.Error("No scene available to append to");
  69208. return null;
  69209. }
  69210. if (!sceneFilename) {
  69211. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69212. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69213. }
  69214. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69215. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69216. return null;
  69217. }
  69218. if (SceneLoader.ShowLoadingScreen) {
  69219. scene.getEngine().displayLoadingUI();
  69220. }
  69221. var loadingToken = {};
  69222. scene._addPendingData(loadingToken);
  69223. var disposeHandler = function () {
  69224. scene._removePendingData(loadingToken);
  69225. scene.getEngine().hideLoadingUI();
  69226. };
  69227. var errorHandler = function (message, exception) {
  69228. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69229. if (onError) {
  69230. onError(scene, errorMessage, exception);
  69231. }
  69232. else {
  69233. BABYLON.Tools.Error(errorMessage);
  69234. // should the exception be thrown?
  69235. }
  69236. disposeHandler();
  69237. };
  69238. var progressHandler = onProgress ? function (event) {
  69239. try {
  69240. onProgress(event);
  69241. }
  69242. catch (e) {
  69243. errorHandler("Error in onProgress callback", e);
  69244. }
  69245. } : undefined;
  69246. var successHandler = function () {
  69247. if (onSuccess) {
  69248. try {
  69249. onSuccess(scene);
  69250. }
  69251. catch (e) {
  69252. errorHandler("Error in onSuccess callback", e);
  69253. }
  69254. }
  69255. scene._removePendingData(loadingToken);
  69256. };
  69257. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69258. if (sceneFilename === "") {
  69259. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69260. }
  69261. if (plugin.load) {
  69262. var syncedPlugin = plugin;
  69263. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  69264. return;
  69265. }
  69266. scene.loadingPluginName = plugin.name;
  69267. successHandler();
  69268. }
  69269. else {
  69270. var asyncedPlugin = plugin;
  69271. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  69272. scene.loadingPluginName = plugin.name;
  69273. successHandler();
  69274. }).catch(function (error) {
  69275. errorHandler(error.message, error);
  69276. });
  69277. }
  69278. if (SceneLoader.ShowLoadingScreen) {
  69279. scene.executeWhenReady(function () {
  69280. scene.getEngine().hideLoadingUI();
  69281. });
  69282. }
  69283. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69284. };
  69285. /**
  69286. * Append a scene
  69287. * @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)
  69288. * @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)
  69289. * @param scene is the instance of BABYLON.Scene to append to
  69290. * @param onProgress a callback with a progress event for each file being loaded
  69291. * @param pluginExtension the extension used to determine the plugin
  69292. * @returns The given scene
  69293. */
  69294. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69295. if (sceneFilename === void 0) { sceneFilename = ""; }
  69296. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69297. if (onProgress === void 0) { onProgress = null; }
  69298. if (pluginExtension === void 0) { pluginExtension = null; }
  69299. return new Promise(function (resolve, reject) {
  69300. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  69301. resolve(scene);
  69302. }, onProgress, function (scene, message, exception) {
  69303. reject(exception || new Error(message));
  69304. }, pluginExtension);
  69305. });
  69306. };
  69307. /**
  69308. * Load a scene into an asset container
  69309. * @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)
  69310. * @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)
  69311. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  69312. * @param onSuccess a callback with the scene when import succeeds
  69313. * @param onProgress a callback with a progress event for each file being loaded
  69314. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69315. * @param pluginExtension the extension used to determine the plugin
  69316. * @returns The loaded plugin
  69317. */
  69318. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69319. if (sceneFilename === void 0) { sceneFilename = ""; }
  69320. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69321. if (onSuccess === void 0) { onSuccess = null; }
  69322. if (onProgress === void 0) { onProgress = null; }
  69323. if (onError === void 0) { onError = null; }
  69324. if (pluginExtension === void 0) { pluginExtension = null; }
  69325. if (!scene) {
  69326. BABYLON.Tools.Error("No scene available to load asset container to");
  69327. return null;
  69328. }
  69329. if (!sceneFilename) {
  69330. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69331. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69332. }
  69333. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69334. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69335. return null;
  69336. }
  69337. var loadingToken = {};
  69338. scene._addPendingData(loadingToken);
  69339. var disposeHandler = function () {
  69340. scene._removePendingData(loadingToken);
  69341. };
  69342. var errorHandler = function (message, exception) {
  69343. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69344. if (onError) {
  69345. onError(scene, errorMessage, exception);
  69346. }
  69347. else {
  69348. BABYLON.Tools.Error(errorMessage);
  69349. // should the exception be thrown?
  69350. }
  69351. disposeHandler();
  69352. };
  69353. var progressHandler = onProgress ? function (event) {
  69354. try {
  69355. onProgress(event);
  69356. }
  69357. catch (e) {
  69358. errorHandler("Error in onProgress callback", e);
  69359. }
  69360. } : undefined;
  69361. var successHandler = function (assets) {
  69362. if (onSuccess) {
  69363. try {
  69364. onSuccess(assets);
  69365. }
  69366. catch (e) {
  69367. errorHandler("Error in onSuccess callback", e);
  69368. }
  69369. }
  69370. scene._removePendingData(loadingToken);
  69371. };
  69372. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69373. if (plugin.loadAssetContainer) {
  69374. var syncedPlugin = plugin;
  69375. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  69376. if (!assetContainer) {
  69377. return;
  69378. }
  69379. scene.loadingPluginName = plugin.name;
  69380. successHandler(assetContainer);
  69381. }
  69382. else if (plugin.loadAssetContainerAsync) {
  69383. var asyncedPlugin = plugin;
  69384. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  69385. scene.loadingPluginName = plugin.name;
  69386. successHandler(assetContainer);
  69387. }).catch(function (error) {
  69388. errorHandler(error.message, error);
  69389. });
  69390. }
  69391. else {
  69392. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  69393. }
  69394. if (SceneLoader.ShowLoadingScreen) {
  69395. scene.executeWhenReady(function () {
  69396. scene.getEngine().hideLoadingUI();
  69397. });
  69398. }
  69399. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69400. };
  69401. /**
  69402. * Load a scene into an asset container
  69403. * @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)
  69404. * @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)
  69405. * @param scene is the instance of BABYLON.Scene to append to
  69406. * @param onProgress a callback with a progress event for each file being loaded
  69407. * @param pluginExtension the extension used to determine the plugin
  69408. * @returns The loaded asset container
  69409. */
  69410. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69411. if (sceneFilename === void 0) { sceneFilename = ""; }
  69412. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69413. if (onProgress === void 0) { onProgress = null; }
  69414. if (pluginExtension === void 0) { pluginExtension = null; }
  69415. return new Promise(function (resolve, reject) {
  69416. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  69417. resolve(assetContainer);
  69418. }, onProgress, function (scene, message, exception) {
  69419. reject(exception || new Error(message));
  69420. }, pluginExtension);
  69421. });
  69422. };
  69423. // Flags
  69424. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  69425. SceneLoader._ShowLoadingScreen = true;
  69426. SceneLoader._CleanBoneMatrixWeights = false;
  69427. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  69428. // Members
  69429. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  69430. SceneLoader._registeredPlugins = {};
  69431. return SceneLoader;
  69432. }());
  69433. BABYLON.SceneLoader = SceneLoader;
  69434. ;
  69435. })(BABYLON || (BABYLON = {}));
  69436. //# sourceMappingURL=babylon.sceneLoader.js.map
  69437. var BABYLON;
  69438. (function (BABYLON) {
  69439. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  69440. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69441. var parsedMaterial = parsedData.materials[index];
  69442. if (parsedMaterial.id === id) {
  69443. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69444. }
  69445. }
  69446. return null;
  69447. };
  69448. var isDescendantOf = function (mesh, names, hierarchyIds) {
  69449. for (var i in names) {
  69450. if (mesh.name === names[i]) {
  69451. hierarchyIds.push(mesh.id);
  69452. return true;
  69453. }
  69454. }
  69455. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  69456. hierarchyIds.push(mesh.id);
  69457. return true;
  69458. }
  69459. return false;
  69460. };
  69461. var logOperation = function (operation, producer) {
  69462. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  69463. };
  69464. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  69465. if (addToScene === void 0) { addToScene = false; }
  69466. var container = new BABYLON.AssetContainer(scene);
  69467. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69468. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69469. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69470. // and avoid problems with multiple concurrent .babylon loads.
  69471. var log = "importScene has failed JSON parse";
  69472. try {
  69473. var parsedData = JSON.parse(data);
  69474. log = "";
  69475. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69476. var index;
  69477. var cache;
  69478. // Lights
  69479. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  69480. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  69481. var parsedLight = parsedData.lights[index];
  69482. var light = BABYLON.Light.Parse(parsedLight, scene);
  69483. if (light) {
  69484. container.lights.push(light);
  69485. log += (index === 0 ? "\n\tLights:" : "");
  69486. log += "\n\t\t" + light.toString(fullDetails);
  69487. }
  69488. }
  69489. }
  69490. // Animations
  69491. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  69492. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  69493. var parsedAnimation = parsedData.animations[index];
  69494. var animation = BABYLON.Animation.Parse(parsedAnimation);
  69495. scene.animations.push(animation);
  69496. container.animations.push(animation);
  69497. log += (index === 0 ? "\n\tAnimations:" : "");
  69498. log += "\n\t\t" + animation.toString(fullDetails);
  69499. }
  69500. }
  69501. // Materials
  69502. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  69503. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69504. var parsedMaterial = parsedData.materials[index];
  69505. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69506. container.materials.push(mat);
  69507. log += (index === 0 ? "\n\tMaterials:" : "");
  69508. log += "\n\t\t" + mat.toString(fullDetails);
  69509. }
  69510. }
  69511. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69512. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  69513. var parsedMultiMaterial = parsedData.multiMaterials[index];
  69514. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69515. container.multiMaterials.push(mmat);
  69516. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  69517. log += "\n\t\t" + mmat.toString(fullDetails);
  69518. }
  69519. }
  69520. // Morph targets
  69521. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69522. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69523. var managerData = _a[_i];
  69524. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  69525. }
  69526. }
  69527. // Skeletons
  69528. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69529. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  69530. var parsedSkeleton = parsedData.skeletons[index];
  69531. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69532. container.skeletons.push(skeleton);
  69533. log += (index === 0 ? "\n\tSkeletons:" : "");
  69534. log += "\n\t\t" + skeleton.toString(fullDetails);
  69535. }
  69536. }
  69537. // Geometries
  69538. var geometries = parsedData.geometries;
  69539. if (geometries !== undefined && geometries !== null) {
  69540. var addedGeometry = new Array();
  69541. // Boxes
  69542. var boxes = geometries.boxes;
  69543. if (boxes !== undefined && boxes !== null) {
  69544. for (index = 0, cache = boxes.length; index < cache; index++) {
  69545. var parsedBox = boxes[index];
  69546. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  69547. }
  69548. }
  69549. // Spheres
  69550. var spheres = geometries.spheres;
  69551. if (spheres !== undefined && spheres !== null) {
  69552. for (index = 0, cache = spheres.length; index < cache; index++) {
  69553. var parsedSphere = spheres[index];
  69554. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  69555. }
  69556. }
  69557. // Cylinders
  69558. var cylinders = geometries.cylinders;
  69559. if (cylinders !== undefined && cylinders !== null) {
  69560. for (index = 0, cache = cylinders.length; index < cache; index++) {
  69561. var parsedCylinder = cylinders[index];
  69562. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  69563. }
  69564. }
  69565. // Toruses
  69566. var toruses = geometries.toruses;
  69567. if (toruses !== undefined && toruses !== null) {
  69568. for (index = 0, cache = toruses.length; index < cache; index++) {
  69569. var parsedTorus = toruses[index];
  69570. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  69571. }
  69572. }
  69573. // Grounds
  69574. var grounds = geometries.grounds;
  69575. if (grounds !== undefined && grounds !== null) {
  69576. for (index = 0, cache = grounds.length; index < cache; index++) {
  69577. var parsedGround = grounds[index];
  69578. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  69579. }
  69580. }
  69581. // Planes
  69582. var planes = geometries.planes;
  69583. if (planes !== undefined && planes !== null) {
  69584. for (index = 0, cache = planes.length; index < cache; index++) {
  69585. var parsedPlane = planes[index];
  69586. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  69587. }
  69588. }
  69589. // TorusKnots
  69590. var torusKnots = geometries.torusKnots;
  69591. if (torusKnots !== undefined && torusKnots !== null) {
  69592. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  69593. var parsedTorusKnot = torusKnots[index];
  69594. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  69595. }
  69596. }
  69597. // VertexData
  69598. var vertexData = geometries.vertexData;
  69599. if (vertexData !== undefined && vertexData !== null) {
  69600. for (index = 0, cache = vertexData.length; index < cache; index++) {
  69601. var parsedVertexData = vertexData[index];
  69602. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  69603. }
  69604. }
  69605. addedGeometry.forEach(function (g) {
  69606. if (g) {
  69607. container.geometries.push(g);
  69608. }
  69609. });
  69610. }
  69611. // Transform nodes
  69612. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  69613. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  69614. var parsedTransformNode = parsedData.transformNodes[index];
  69615. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  69616. container.transformNodes.push(node);
  69617. }
  69618. }
  69619. // Meshes
  69620. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69621. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69622. var parsedMesh = parsedData.meshes[index];
  69623. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69624. container.meshes.push(mesh);
  69625. log += (index === 0 ? "\n\tMeshes:" : "");
  69626. log += "\n\t\t" + mesh.toString(fullDetails);
  69627. }
  69628. }
  69629. // Cameras
  69630. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  69631. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  69632. var parsedCamera = parsedData.cameras[index];
  69633. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  69634. container.cameras.push(camera);
  69635. log += (index === 0 ? "\n\tCameras:" : "");
  69636. log += "\n\t\t" + camera.toString(fullDetails);
  69637. }
  69638. }
  69639. // Browsing all the graph to connect the dots
  69640. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  69641. var camera = scene.cameras[index];
  69642. if (camera._waitingParentId) {
  69643. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  69644. camera._waitingParentId = null;
  69645. }
  69646. }
  69647. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69648. var light_1 = scene.lights[index];
  69649. if (light_1 && light_1._waitingParentId) {
  69650. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  69651. light_1._waitingParentId = null;
  69652. }
  69653. }
  69654. // Sounds
  69655. // TODO: add sound
  69656. var loadedSounds = [];
  69657. var loadedSound;
  69658. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69659. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69660. var parsedSound = parsedData.sounds[index];
  69661. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69662. if (!parsedSound.url)
  69663. parsedSound.url = parsedSound.name;
  69664. if (!loadedSounds[parsedSound.url]) {
  69665. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69666. loadedSounds[parsedSound.url] = loadedSound;
  69667. container.sounds.push(loadedSound);
  69668. }
  69669. else {
  69670. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69671. }
  69672. }
  69673. else {
  69674. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69675. }
  69676. }
  69677. }
  69678. loadedSounds = [];
  69679. // Connect parents & children and parse actions
  69680. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  69681. var transformNode = scene.transformNodes[index];
  69682. if (transformNode._waitingParentId) {
  69683. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  69684. transformNode._waitingParentId = null;
  69685. }
  69686. }
  69687. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69688. var mesh = scene.meshes[index];
  69689. if (mesh._waitingParentId) {
  69690. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  69691. mesh._waitingParentId = null;
  69692. }
  69693. if (mesh._waitingActions) {
  69694. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  69695. mesh._waitingActions = null;
  69696. }
  69697. }
  69698. // freeze world matrix application
  69699. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69700. var currentMesh = scene.meshes[index];
  69701. if (currentMesh._waitingFreezeWorldMatrix) {
  69702. currentMesh.freezeWorldMatrix();
  69703. currentMesh._waitingFreezeWorldMatrix = null;
  69704. }
  69705. else {
  69706. currentMesh.computeWorldMatrix(true);
  69707. }
  69708. }
  69709. // Shadows
  69710. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  69711. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  69712. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  69713. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  69714. // SG would be available on their associated lights
  69715. }
  69716. }
  69717. // Lights exclusions / inclusions
  69718. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69719. var light_2 = scene.lights[index];
  69720. // Excluded check
  69721. if (light_2._excludedMeshesIds.length > 0) {
  69722. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  69723. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  69724. if (excludedMesh) {
  69725. light_2.excludedMeshes.push(excludedMesh);
  69726. }
  69727. }
  69728. light_2._excludedMeshesIds = [];
  69729. }
  69730. // Included check
  69731. if (light_2._includedOnlyMeshesIds.length > 0) {
  69732. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  69733. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  69734. if (includedOnlyMesh) {
  69735. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  69736. }
  69737. }
  69738. light_2._includedOnlyMeshesIds = [];
  69739. }
  69740. }
  69741. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  69742. // Actions (scene)
  69743. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  69744. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  69745. }
  69746. if (!addToScene) {
  69747. container.removeAllFromScene();
  69748. }
  69749. }
  69750. catch (err) {
  69751. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  69752. if (onError) {
  69753. onError(msg, err);
  69754. }
  69755. else {
  69756. BABYLON.Tools.Log(msg);
  69757. throw err;
  69758. }
  69759. }
  69760. finally {
  69761. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69762. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69763. }
  69764. }
  69765. return container;
  69766. };
  69767. BABYLON.SceneLoader.RegisterPlugin({
  69768. name: "babylon.js",
  69769. extensions: ".babylon",
  69770. canDirectLoad: function (data) {
  69771. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  69772. return true;
  69773. }
  69774. return false;
  69775. },
  69776. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  69777. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69778. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69779. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69780. // and avoid problems with multiple concurrent .babylon loads.
  69781. var log = "importMesh has failed JSON parse";
  69782. try {
  69783. var parsedData = JSON.parse(data);
  69784. log = "";
  69785. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69786. if (!meshesNames) {
  69787. meshesNames = null;
  69788. }
  69789. else if (!Array.isArray(meshesNames)) {
  69790. meshesNames = [meshesNames];
  69791. }
  69792. var hierarchyIds = new Array();
  69793. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69794. var loadedSkeletonsIds = [];
  69795. var loadedMaterialsIds = [];
  69796. var index;
  69797. var cache;
  69798. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69799. var parsedMesh = parsedData.meshes[index];
  69800. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  69801. if (meshesNames !== null) {
  69802. // Remove found mesh name from list.
  69803. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  69804. }
  69805. //Geometry?
  69806. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  69807. //does the file contain geometries?
  69808. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  69809. //find the correct geometry and add it to the scene
  69810. var found = false;
  69811. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  69812. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  69813. return;
  69814. }
  69815. else {
  69816. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  69817. if (parsedGeometryData.id === parsedMesh.geometryId) {
  69818. switch (geometryType) {
  69819. case "boxes":
  69820. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  69821. break;
  69822. case "spheres":
  69823. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  69824. break;
  69825. case "cylinders":
  69826. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  69827. break;
  69828. case "toruses":
  69829. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  69830. break;
  69831. case "grounds":
  69832. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  69833. break;
  69834. case "planes":
  69835. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  69836. break;
  69837. case "torusKnots":
  69838. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  69839. break;
  69840. case "vertexData":
  69841. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  69842. break;
  69843. }
  69844. found = true;
  69845. }
  69846. });
  69847. }
  69848. });
  69849. if (found === false) {
  69850. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  69851. }
  69852. }
  69853. }
  69854. // Material ?
  69855. if (parsedMesh.materialId) {
  69856. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  69857. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69858. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  69859. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  69860. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  69861. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  69862. var subMatId = parsedMultiMaterial.materials[matIndex];
  69863. loadedMaterialsIds.push(subMatId);
  69864. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  69865. if (mat) {
  69866. log += "\n\tMaterial " + mat.toString(fullDetails);
  69867. }
  69868. }
  69869. loadedMaterialsIds.push(parsedMultiMaterial.id);
  69870. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69871. if (mmat) {
  69872. materialFound = true;
  69873. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  69874. }
  69875. break;
  69876. }
  69877. }
  69878. }
  69879. if (materialFound === false) {
  69880. loadedMaterialsIds.push(parsedMesh.materialId);
  69881. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  69882. if (!mat) {
  69883. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  69884. }
  69885. else {
  69886. log += "\n\tMaterial " + mat.toString(fullDetails);
  69887. }
  69888. }
  69889. }
  69890. // Skeleton ?
  69891. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69892. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  69893. if (skeletonAlreadyLoaded === false) {
  69894. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  69895. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  69896. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  69897. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69898. skeletons.push(skeleton);
  69899. loadedSkeletonsIds.push(parsedSkeleton.id);
  69900. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  69901. }
  69902. }
  69903. }
  69904. }
  69905. // Morph targets ?
  69906. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69907. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69908. var managerData = _a[_i];
  69909. BABYLON.MorphTargetManager.Parse(managerData, scene);
  69910. }
  69911. }
  69912. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69913. meshes.push(mesh);
  69914. log += "\n\tMesh " + mesh.toString(fullDetails);
  69915. }
  69916. }
  69917. // Connecting parents
  69918. var currentMesh;
  69919. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69920. currentMesh = scene.meshes[index];
  69921. if (currentMesh._waitingParentId) {
  69922. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  69923. currentMesh._waitingParentId = null;
  69924. }
  69925. }
  69926. // freeze and compute world matrix application
  69927. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69928. currentMesh = scene.meshes[index];
  69929. if (currentMesh._waitingFreezeWorldMatrix) {
  69930. currentMesh.freezeWorldMatrix();
  69931. currentMesh._waitingFreezeWorldMatrix = null;
  69932. }
  69933. else {
  69934. currentMesh.computeWorldMatrix(true);
  69935. }
  69936. }
  69937. }
  69938. // Particles
  69939. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  69940. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  69941. if (parser) {
  69942. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  69943. var parsedParticleSystem = parsedData.particleSystems[index];
  69944. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  69945. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  69946. }
  69947. }
  69948. }
  69949. }
  69950. return true;
  69951. }
  69952. catch (err) {
  69953. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  69954. if (onError) {
  69955. onError(msg, err);
  69956. }
  69957. else {
  69958. BABYLON.Tools.Log(msg);
  69959. throw err;
  69960. }
  69961. }
  69962. finally {
  69963. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69964. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69965. }
  69966. }
  69967. return false;
  69968. },
  69969. load: function (scene, data, rootUrl, onError) {
  69970. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69971. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69972. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69973. // and avoid problems with multiple concurrent .babylon loads.
  69974. var log = "importScene has failed JSON parse";
  69975. try {
  69976. var parsedData = JSON.parse(data);
  69977. log = "";
  69978. // Scene
  69979. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  69980. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  69981. }
  69982. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  69983. scene.autoClear = parsedData.autoClear;
  69984. }
  69985. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  69986. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  69987. }
  69988. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  69989. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  69990. }
  69991. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  69992. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  69993. }
  69994. // Fog
  69995. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  69996. scene.fogMode = parsedData.fogMode;
  69997. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  69998. scene.fogStart = parsedData.fogStart;
  69999. scene.fogEnd = parsedData.fogEnd;
  70000. scene.fogDensity = parsedData.fogDensity;
  70001. log += "\tFog mode for scene: ";
  70002. switch (scene.fogMode) {
  70003. // getters not compiling, so using hardcoded
  70004. case 1:
  70005. log += "exp\n";
  70006. break;
  70007. case 2:
  70008. log += "exp2\n";
  70009. break;
  70010. case 3:
  70011. log += "linear\n";
  70012. break;
  70013. }
  70014. }
  70015. //Physics
  70016. if (parsedData.physicsEnabled) {
  70017. var physicsPlugin;
  70018. if (parsedData.physicsEngine === "cannon") {
  70019. physicsPlugin = new BABYLON.CannonJSPlugin();
  70020. }
  70021. else if (parsedData.physicsEngine === "oimo") {
  70022. physicsPlugin = new BABYLON.OimoJSPlugin();
  70023. }
  70024. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  70025. //else - default engine, which is currently oimo
  70026. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  70027. scene.enablePhysics(physicsGravity, physicsPlugin);
  70028. }
  70029. // Metadata
  70030. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  70031. scene.metadata = parsedData.metadata;
  70032. }
  70033. //collisions, if defined. otherwise, default is true
  70034. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  70035. scene.collisionsEnabled = parsedData.collisionsEnabled;
  70036. }
  70037. scene.workerCollisions = !!parsedData.workerCollisions;
  70038. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  70039. if (!container) {
  70040. return false;
  70041. }
  70042. if (parsedData.autoAnimate) {
  70043. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  70044. }
  70045. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  70046. scene.setActiveCameraByID(parsedData.activeCameraID);
  70047. }
  70048. // Environment texture
  70049. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  70050. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  70051. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  70052. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  70053. if (parsedData.environmentTextureRotationY) {
  70054. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  70055. }
  70056. scene.environmentTexture = hdrTexture;
  70057. }
  70058. else {
  70059. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  70060. if (parsedData.environmentTextureRotationY) {
  70061. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  70062. }
  70063. scene.environmentTexture = cubeTexture;
  70064. }
  70065. if (parsedData.createDefaultSkybox === true) {
  70066. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  70067. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  70068. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  70069. }
  70070. }
  70071. // Finish
  70072. return true;
  70073. }
  70074. catch (err) {
  70075. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  70076. if (onError) {
  70077. onError(msg, err);
  70078. }
  70079. else {
  70080. BABYLON.Tools.Log(msg);
  70081. throw err;
  70082. }
  70083. }
  70084. finally {
  70085. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70086. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70087. }
  70088. }
  70089. return false;
  70090. },
  70091. loadAssetContainer: function (scene, data, rootUrl, onError) {
  70092. var container = loadAssetContainer(scene, data, rootUrl, onError);
  70093. return container;
  70094. }
  70095. });
  70096. })(BABYLON || (BABYLON = {}));
  70097. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  70098. var BABYLON;
  70099. (function (BABYLON) {
  70100. var FilesInput = /** @class */ (function () {
  70101. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  70102. this.onProcessFileCallback = function () { return true; };
  70103. this._engine = engine;
  70104. this._currentScene = scene;
  70105. this._sceneLoadedCallback = sceneLoadedCallback;
  70106. this._progressCallback = progressCallback;
  70107. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  70108. this._textureLoadingCallback = textureLoadingCallback;
  70109. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  70110. this._onReloadCallback = onReloadCallback;
  70111. this._errorCallback = errorCallback;
  70112. }
  70113. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  70114. var _this = this;
  70115. if (elementToMonitor) {
  70116. this._elementToMonitor = elementToMonitor;
  70117. this._dragEnterHandler = function (e) { _this.drag(e); };
  70118. this._dragOverHandler = function (e) { _this.drag(e); };
  70119. this._dropHandler = function (e) { _this.drop(e); };
  70120. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  70121. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  70122. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  70123. }
  70124. };
  70125. FilesInput.prototype.dispose = function () {
  70126. if (!this._elementToMonitor) {
  70127. return;
  70128. }
  70129. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  70130. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  70131. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  70132. };
  70133. FilesInput.prototype.renderFunction = function () {
  70134. if (this._additionalRenderLoopLogicCallback) {
  70135. this._additionalRenderLoopLogicCallback();
  70136. }
  70137. if (this._currentScene) {
  70138. if (this._textureLoadingCallback) {
  70139. var remaining = this._currentScene.getWaitingItemsCount();
  70140. if (remaining > 0) {
  70141. this._textureLoadingCallback(remaining);
  70142. }
  70143. }
  70144. this._currentScene.render();
  70145. }
  70146. };
  70147. FilesInput.prototype.drag = function (e) {
  70148. e.stopPropagation();
  70149. e.preventDefault();
  70150. };
  70151. FilesInput.prototype.drop = function (eventDrop) {
  70152. eventDrop.stopPropagation();
  70153. eventDrop.preventDefault();
  70154. this.loadFiles(eventDrop);
  70155. };
  70156. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  70157. var _this = this;
  70158. var reader = folder.createReader();
  70159. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  70160. reader.readEntries(function (entries) {
  70161. remaining.count += entries.length;
  70162. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  70163. var entry = entries_1[_i];
  70164. if (entry.isFile) {
  70165. entry.file(function (file) {
  70166. file.correctName = relativePath + file.name;
  70167. files.push(file);
  70168. if (--remaining.count === 0) {
  70169. callback();
  70170. }
  70171. });
  70172. }
  70173. else if (entry.isDirectory) {
  70174. _this._traverseFolder(entry, files, remaining, callback);
  70175. }
  70176. }
  70177. if (--remaining.count) {
  70178. callback();
  70179. }
  70180. });
  70181. };
  70182. FilesInput.prototype._processFiles = function (files) {
  70183. for (var i = 0; i < files.length; i++) {
  70184. var name = files[i].correctName.toLowerCase();
  70185. var extension = name.split('.').pop();
  70186. if (!this.onProcessFileCallback(files[i], name, extension)) {
  70187. continue;
  70188. }
  70189. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  70190. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  70191. this._sceneFileToLoad = files[i];
  70192. }
  70193. else {
  70194. FilesInput.FilesToLoad[name] = files[i];
  70195. }
  70196. }
  70197. };
  70198. FilesInput.prototype.loadFiles = function (event) {
  70199. var _this = this;
  70200. if (this._startingProcessingFilesCallback)
  70201. this._startingProcessingFilesCallback();
  70202. // Handling data transfer via drag'n'drop
  70203. if (event && event.dataTransfer && event.dataTransfer.files) {
  70204. this._filesToLoad = event.dataTransfer.files;
  70205. }
  70206. // Handling files from input files
  70207. if (event && event.target && event.target.files) {
  70208. this._filesToLoad = event.target.files;
  70209. }
  70210. if (this._filesToLoad && this._filesToLoad.length > 0) {
  70211. var files_1 = new Array();
  70212. var folders = [];
  70213. var items = event.dataTransfer ? event.dataTransfer.items : null;
  70214. for (var i = 0; i < this._filesToLoad.length; i++) {
  70215. var fileToLoad = this._filesToLoad[i];
  70216. var name_1 = fileToLoad.name.toLowerCase();
  70217. var entry = void 0;
  70218. fileToLoad.correctName = name_1;
  70219. if (items) {
  70220. var item = items[i];
  70221. if (item.getAsEntry) {
  70222. entry = item.getAsEntry();
  70223. }
  70224. else if (item.webkitGetAsEntry) {
  70225. entry = item.webkitGetAsEntry();
  70226. }
  70227. }
  70228. if (!entry) {
  70229. files_1.push(fileToLoad);
  70230. }
  70231. else {
  70232. if (entry.isDirectory) {
  70233. folders.push(entry);
  70234. }
  70235. else {
  70236. files_1.push(fileToLoad);
  70237. }
  70238. }
  70239. }
  70240. if (folders.length === 0) {
  70241. this._processFiles(files_1);
  70242. this._processReload();
  70243. }
  70244. else {
  70245. var remaining = { count: folders.length };
  70246. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  70247. var folder = folders_1[_i];
  70248. this._traverseFolder(folder, files_1, remaining, function () {
  70249. _this._processFiles(files_1);
  70250. if (remaining.count === 0) {
  70251. _this._processReload();
  70252. }
  70253. });
  70254. }
  70255. }
  70256. }
  70257. };
  70258. FilesInput.prototype._processReload = function () {
  70259. if (this._onReloadCallback) {
  70260. this._onReloadCallback(this._sceneFileToLoad);
  70261. }
  70262. else {
  70263. this.reload();
  70264. }
  70265. };
  70266. FilesInput.prototype.reload = function () {
  70267. var _this = this;
  70268. // If a scene file has been provided
  70269. if (this._sceneFileToLoad) {
  70270. if (this._currentScene) {
  70271. if (BABYLON.Tools.errorsCount > 0) {
  70272. BABYLON.Tools.ClearLogCache();
  70273. }
  70274. this._engine.stopRenderLoop();
  70275. }
  70276. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  70277. if (_this._progressCallback) {
  70278. _this._progressCallback(progress);
  70279. }
  70280. }).then(function (scene) {
  70281. if (_this._currentScene) {
  70282. _this._currentScene.dispose();
  70283. }
  70284. _this._currentScene = scene;
  70285. if (_this._sceneLoadedCallback) {
  70286. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  70287. }
  70288. // Wait for textures and shaders to be ready
  70289. _this._currentScene.executeWhenReady(function () {
  70290. _this._engine.runRenderLoop(function () {
  70291. _this.renderFunction();
  70292. });
  70293. });
  70294. }).catch(function (error) {
  70295. if (_this._errorCallback) {
  70296. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  70297. }
  70298. });
  70299. }
  70300. else {
  70301. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  70302. }
  70303. };
  70304. FilesInput.FilesToLoad = {};
  70305. return FilesInput;
  70306. }());
  70307. BABYLON.FilesInput = FilesInput;
  70308. })(BABYLON || (BABYLON = {}));
  70309. //# sourceMappingURL=babylon.filesInput.js.map
  70310. var BABYLON;
  70311. (function (BABYLON) {
  70312. var Tags = /** @class */ (function () {
  70313. function Tags() {
  70314. }
  70315. Tags.EnableFor = function (obj) {
  70316. obj._tags = obj._tags || {};
  70317. obj.hasTags = function () {
  70318. return Tags.HasTags(obj);
  70319. };
  70320. obj.addTags = function (tagsString) {
  70321. return Tags.AddTagsTo(obj, tagsString);
  70322. };
  70323. obj.removeTags = function (tagsString) {
  70324. return Tags.RemoveTagsFrom(obj, tagsString);
  70325. };
  70326. obj.matchesTagsQuery = function (tagsQuery) {
  70327. return Tags.MatchesQuery(obj, tagsQuery);
  70328. };
  70329. };
  70330. Tags.DisableFor = function (obj) {
  70331. delete obj._tags;
  70332. delete obj.hasTags;
  70333. delete obj.addTags;
  70334. delete obj.removeTags;
  70335. delete obj.matchesTagsQuery;
  70336. };
  70337. Tags.HasTags = function (obj) {
  70338. if (!obj._tags) {
  70339. return false;
  70340. }
  70341. return !BABYLON.Tools.IsEmpty(obj._tags);
  70342. };
  70343. Tags.GetTags = function (obj, asString) {
  70344. if (asString === void 0) { asString = true; }
  70345. if (!obj._tags) {
  70346. return null;
  70347. }
  70348. if (asString) {
  70349. var tagsArray = [];
  70350. for (var tag in obj._tags) {
  70351. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  70352. tagsArray.push(tag);
  70353. }
  70354. }
  70355. return tagsArray.join(" ");
  70356. }
  70357. else {
  70358. return obj._tags;
  70359. }
  70360. };
  70361. // the tags 'true' and 'false' are reserved and cannot be used as tags
  70362. // a tag cannot start with '||', '&&', and '!'
  70363. // it cannot contain whitespaces
  70364. Tags.AddTagsTo = function (obj, tagsString) {
  70365. if (!tagsString) {
  70366. return;
  70367. }
  70368. if (typeof tagsString !== "string") {
  70369. return;
  70370. }
  70371. var tags = tagsString.split(" ");
  70372. tags.forEach(function (tag, index, array) {
  70373. Tags._AddTagTo(obj, tag);
  70374. });
  70375. };
  70376. Tags._AddTagTo = function (obj, tag) {
  70377. tag = tag.trim();
  70378. if (tag === "" || tag === "true" || tag === "false") {
  70379. return;
  70380. }
  70381. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  70382. return;
  70383. }
  70384. Tags.EnableFor(obj);
  70385. obj._tags[tag] = true;
  70386. };
  70387. Tags.RemoveTagsFrom = function (obj, tagsString) {
  70388. if (!Tags.HasTags(obj)) {
  70389. return;
  70390. }
  70391. var tags = tagsString.split(" ");
  70392. for (var t in tags) {
  70393. Tags._RemoveTagFrom(obj, tags[t]);
  70394. }
  70395. };
  70396. Tags._RemoveTagFrom = function (obj, tag) {
  70397. delete obj._tags[tag];
  70398. };
  70399. Tags.MatchesQuery = function (obj, tagsQuery) {
  70400. if (tagsQuery === undefined) {
  70401. return true;
  70402. }
  70403. if (tagsQuery === "") {
  70404. return Tags.HasTags(obj);
  70405. }
  70406. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  70407. };
  70408. return Tags;
  70409. }());
  70410. BABYLON.Tags = Tags;
  70411. })(BABYLON || (BABYLON = {}));
  70412. //# sourceMappingURL=babylon.tags.js.map
  70413. var BABYLON;
  70414. (function (BABYLON) {
  70415. /**
  70416. * Class used to evalaute queries containing `and` and `or` operators
  70417. */
  70418. var AndOrNotEvaluator = /** @class */ (function () {
  70419. function AndOrNotEvaluator() {
  70420. }
  70421. /**
  70422. * Evaluate a query
  70423. * @param query defines the query to evaluate
  70424. * @param evaluateCallback defines the callback used to filter result
  70425. * @returns true if the query matches
  70426. */
  70427. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  70428. if (!query.match(/\([^\(\)]*\)/g)) {
  70429. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  70430. }
  70431. else {
  70432. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  70433. // remove parenthesis
  70434. r = r.slice(1, r.length - 1);
  70435. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  70436. });
  70437. }
  70438. if (query === "true") {
  70439. return true;
  70440. }
  70441. if (query === "false") {
  70442. return false;
  70443. }
  70444. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  70445. };
  70446. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  70447. evaluateCallback = evaluateCallback || (function (r) {
  70448. return r === "true" ? true : false;
  70449. });
  70450. var result;
  70451. var or = parenthesisContent.split("||");
  70452. for (var i in or) {
  70453. if (or.hasOwnProperty(i)) {
  70454. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  70455. var and = ori.split("&&");
  70456. if (and.length > 1) {
  70457. for (var j = 0; j < and.length; ++j) {
  70458. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  70459. if (andj !== "true" && andj !== "false") {
  70460. if (andj[0] === "!") {
  70461. result = !evaluateCallback(andj.substring(1));
  70462. }
  70463. else {
  70464. result = evaluateCallback(andj);
  70465. }
  70466. }
  70467. else {
  70468. result = andj === "true" ? true : false;
  70469. }
  70470. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  70471. ori = "false";
  70472. break;
  70473. }
  70474. }
  70475. }
  70476. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  70477. result = true;
  70478. break;
  70479. }
  70480. // result equals false (or undefined)
  70481. if (ori !== "true" && ori !== "false") {
  70482. if (ori[0] === "!") {
  70483. result = !evaluateCallback(ori.substring(1));
  70484. }
  70485. else {
  70486. result = evaluateCallback(ori);
  70487. }
  70488. }
  70489. else {
  70490. result = ori === "true" ? true : false;
  70491. }
  70492. }
  70493. }
  70494. // the whole parenthesis scope is replaced by 'true' or 'false'
  70495. return result ? "true" : "false";
  70496. };
  70497. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  70498. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  70499. // remove whitespaces
  70500. r = r.replace(/[\s]/g, function () { return ""; });
  70501. return r.length % 2 ? "!" : "";
  70502. });
  70503. booleanString = booleanString.trim();
  70504. if (booleanString === "!true") {
  70505. booleanString = "false";
  70506. }
  70507. else if (booleanString === "!false") {
  70508. booleanString = "true";
  70509. }
  70510. return booleanString;
  70511. };
  70512. return AndOrNotEvaluator;
  70513. }());
  70514. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  70515. })(BABYLON || (BABYLON = {}));
  70516. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  70517. var BABYLON;
  70518. (function (BABYLON) {
  70519. /**
  70520. * Class used to enable access to IndexedDB
  70521. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  70522. */
  70523. var Database = /** @class */ (function () {
  70524. /**
  70525. * Creates a new Database
  70526. * @param urlToScene defines the url to load the scene
  70527. * @param callbackManifestChecked defines the callback to use when manifest is checked
  70528. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  70529. */
  70530. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  70531. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  70532. var _this = this;
  70533. // Handling various flavors of prefixed version of IndexedDB
  70534. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  70535. this.callbackManifestChecked = callbackManifestChecked;
  70536. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  70537. this.db = null;
  70538. this._enableSceneOffline = false;
  70539. this._enableTexturesOffline = false;
  70540. this.manifestVersionFound = 0;
  70541. this.mustUpdateRessources = false;
  70542. this.hasReachedQuota = false;
  70543. if (!Database.IDBStorageEnabled) {
  70544. this.callbackManifestChecked(true);
  70545. }
  70546. else {
  70547. if (disableManifestCheck) {
  70548. this._enableSceneOffline = true;
  70549. this._enableTexturesOffline = true;
  70550. this.manifestVersionFound = 1;
  70551. BABYLON.Tools.SetImmediate(function () {
  70552. _this.callbackManifestChecked(true);
  70553. });
  70554. }
  70555. else {
  70556. this._checkManifestFile();
  70557. }
  70558. }
  70559. }
  70560. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  70561. /**
  70562. * Gets a boolean indicating if scene must be saved in the database
  70563. */
  70564. get: function () {
  70565. return this._enableSceneOffline;
  70566. },
  70567. enumerable: true,
  70568. configurable: true
  70569. });
  70570. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  70571. /**
  70572. * Gets a boolean indicating if textures must be saved in the database
  70573. */
  70574. get: function () {
  70575. return this._enableTexturesOffline;
  70576. },
  70577. enumerable: true,
  70578. configurable: true
  70579. });
  70580. Database.prototype._checkManifestFile = function () {
  70581. var _this = this;
  70582. var noManifestFile = function () {
  70583. _this._enableSceneOffline = false;
  70584. _this._enableTexturesOffline = false;
  70585. _this.callbackManifestChecked(false);
  70586. };
  70587. var timeStampUsed = false;
  70588. var manifestURL = this.currentSceneUrl + ".manifest";
  70589. var xhr = new XMLHttpRequest();
  70590. if (navigator.onLine) {
  70591. // Adding a timestamp to by-pass browsers' cache
  70592. timeStampUsed = true;
  70593. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  70594. }
  70595. xhr.open("GET", manifestURL, true);
  70596. xhr.addEventListener("load", function () {
  70597. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70598. try {
  70599. var manifestFile = JSON.parse(xhr.response);
  70600. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  70601. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  70602. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  70603. _this.manifestVersionFound = manifestFile.version;
  70604. }
  70605. if (_this.callbackManifestChecked) {
  70606. _this.callbackManifestChecked(true);
  70607. }
  70608. }
  70609. catch (ex) {
  70610. noManifestFile();
  70611. }
  70612. }
  70613. else {
  70614. noManifestFile();
  70615. }
  70616. }, false);
  70617. xhr.addEventListener("error", function (event) {
  70618. if (timeStampUsed) {
  70619. timeStampUsed = false;
  70620. // Let's retry without the timeStamp
  70621. // It could fail when coupled with HTML5 Offline API
  70622. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  70623. xhr.open("GET", retryManifestURL, true);
  70624. xhr.send();
  70625. }
  70626. else {
  70627. noManifestFile();
  70628. }
  70629. }, false);
  70630. try {
  70631. xhr.send();
  70632. }
  70633. catch (ex) {
  70634. BABYLON.Tools.Error("Error on XHR send request.");
  70635. this.callbackManifestChecked(false);
  70636. }
  70637. };
  70638. /**
  70639. * Open the database and make it available
  70640. * @param successCallback defines the callback to call on success
  70641. * @param errorCallback defines the callback to call on error
  70642. */
  70643. Database.prototype.openAsync = function (successCallback, errorCallback) {
  70644. var _this = this;
  70645. var handleError = function () {
  70646. _this.isSupported = false;
  70647. if (errorCallback)
  70648. errorCallback();
  70649. };
  70650. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  70651. // Your browser doesn't support IndexedDB
  70652. this.isSupported = false;
  70653. if (errorCallback)
  70654. errorCallback();
  70655. }
  70656. else {
  70657. // If the DB hasn't been opened or created yet
  70658. if (!this.db) {
  70659. this.hasReachedQuota = false;
  70660. this.isSupported = true;
  70661. var request = this.idbFactory.open("babylonjs", 1);
  70662. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  70663. request.onerror = function (event) {
  70664. handleError();
  70665. };
  70666. // executes when a version change transaction cannot complete due to other active transactions
  70667. request.onblocked = function (event) {
  70668. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  70669. handleError();
  70670. };
  70671. // DB has been opened successfully
  70672. request.onsuccess = function (event) {
  70673. _this.db = request.result;
  70674. successCallback();
  70675. };
  70676. // Initialization of the DB. Creating Scenes & Textures stores
  70677. request.onupgradeneeded = function (event) {
  70678. _this.db = (event.target).result;
  70679. if (_this.db) {
  70680. try {
  70681. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  70682. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  70683. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  70684. }
  70685. catch (ex) {
  70686. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  70687. handleError();
  70688. }
  70689. }
  70690. };
  70691. }
  70692. // DB has already been created and opened
  70693. else {
  70694. if (successCallback)
  70695. successCallback();
  70696. }
  70697. }
  70698. };
  70699. /**
  70700. * Loads an image from the database
  70701. * @param url defines the url to load from
  70702. * @param image defines the target DOM image
  70703. */
  70704. Database.prototype.loadImageFromDB = function (url, image) {
  70705. var _this = this;
  70706. var completeURL = Database._ReturnFullUrlLocation(url);
  70707. var saveAndLoadImage = function () {
  70708. if (!_this.hasReachedQuota && _this.db !== null) {
  70709. // the texture is not yet in the DB, let's try to save it
  70710. _this._saveImageIntoDBAsync(completeURL, image);
  70711. }
  70712. // If the texture is not in the DB and we've reached the DB quota limit
  70713. // let's load it directly from the web
  70714. else {
  70715. image.src = url;
  70716. }
  70717. };
  70718. if (!this.mustUpdateRessources) {
  70719. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  70720. }
  70721. // First time we're download the images or update requested in the manifest file by a version change
  70722. else {
  70723. saveAndLoadImage();
  70724. }
  70725. };
  70726. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  70727. if (this.isSupported && this.db !== null) {
  70728. var texture;
  70729. var transaction = this.db.transaction(["textures"]);
  70730. transaction.onabort = function (event) {
  70731. image.src = url;
  70732. };
  70733. transaction.oncomplete = function (event) {
  70734. var blobTextureURL;
  70735. if (texture) {
  70736. var URL = window.URL || window.webkitURL;
  70737. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  70738. image.onerror = function () {
  70739. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  70740. image.src = url;
  70741. };
  70742. image.src = blobTextureURL;
  70743. }
  70744. else {
  70745. notInDBCallback();
  70746. }
  70747. };
  70748. var getRequest = transaction.objectStore("textures").get(url);
  70749. getRequest.onsuccess = function (event) {
  70750. texture = (event.target).result;
  70751. };
  70752. getRequest.onerror = function (event) {
  70753. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  70754. image.src = url;
  70755. };
  70756. }
  70757. else {
  70758. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70759. image.src = url;
  70760. }
  70761. };
  70762. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  70763. var _this = this;
  70764. if (this.isSupported) {
  70765. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  70766. var generateBlobUrl = function () {
  70767. var blobTextureURL;
  70768. if (blob) {
  70769. var URL = window.URL || window.webkitURL;
  70770. try {
  70771. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  70772. }
  70773. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  70774. catch (ex) {
  70775. blobTextureURL = URL.createObjectURL(blob);
  70776. }
  70777. }
  70778. if (blobTextureURL) {
  70779. image.src = blobTextureURL;
  70780. }
  70781. };
  70782. if (Database.IsUASupportingBlobStorage) { // Create XHR
  70783. var xhr = new XMLHttpRequest(), blob;
  70784. xhr.open("GET", url, true);
  70785. xhr.responseType = "blob";
  70786. xhr.addEventListener("load", function () {
  70787. if (xhr.status === 200 && _this.db) {
  70788. // Blob as response (XHR2)
  70789. blob = xhr.response;
  70790. var transaction = _this.db.transaction(["textures"], "readwrite");
  70791. // the transaction could abort because of a QuotaExceededError error
  70792. transaction.onabort = function (event) {
  70793. try {
  70794. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70795. var srcElement = (event.srcElement || event.target);
  70796. var error = srcElement.error;
  70797. if (error && error.name === "QuotaExceededError") {
  70798. _this.hasReachedQuota = true;
  70799. }
  70800. }
  70801. catch (ex) { }
  70802. generateBlobUrl();
  70803. };
  70804. transaction.oncomplete = function (event) {
  70805. generateBlobUrl();
  70806. };
  70807. var newTexture = { textureUrl: url, data: blob };
  70808. try {
  70809. // Put the blob into the dabase
  70810. var addRequest = transaction.objectStore("textures").put(newTexture);
  70811. addRequest.onsuccess = function (event) {
  70812. };
  70813. addRequest.onerror = function (event) {
  70814. generateBlobUrl();
  70815. };
  70816. }
  70817. catch (ex) {
  70818. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  70819. if (ex.code === 25) {
  70820. Database.IsUASupportingBlobStorage = false;
  70821. }
  70822. image.src = url;
  70823. }
  70824. }
  70825. else {
  70826. image.src = url;
  70827. }
  70828. }, false);
  70829. xhr.addEventListener("error", function (event) {
  70830. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  70831. image.src = url;
  70832. }, false);
  70833. xhr.send();
  70834. }
  70835. else {
  70836. image.src = url;
  70837. }
  70838. }
  70839. else {
  70840. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70841. image.src = url;
  70842. }
  70843. };
  70844. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  70845. var _this = this;
  70846. var updateVersion = function () {
  70847. // the version is not yet in the DB or we need to update it
  70848. _this._saveVersionIntoDBAsync(url, versionLoaded);
  70849. };
  70850. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  70851. };
  70852. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  70853. var _this = this;
  70854. if (this.isSupported && this.db) {
  70855. var version;
  70856. try {
  70857. var transaction = this.db.transaction(["versions"]);
  70858. transaction.oncomplete = function (event) {
  70859. if (version) {
  70860. // If the version in the JSON file is different from the version in DB
  70861. if (_this.manifestVersionFound !== version.data) {
  70862. _this.mustUpdateRessources = true;
  70863. updateInDBCallback();
  70864. }
  70865. else {
  70866. callback(version.data);
  70867. }
  70868. }
  70869. // version was not found in DB
  70870. else {
  70871. _this.mustUpdateRessources = true;
  70872. updateInDBCallback();
  70873. }
  70874. };
  70875. transaction.onabort = function (event) {
  70876. callback(-1);
  70877. };
  70878. var getRequest = transaction.objectStore("versions").get(url);
  70879. getRequest.onsuccess = function (event) {
  70880. version = (event.target).result;
  70881. };
  70882. getRequest.onerror = function (event) {
  70883. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  70884. callback(-1);
  70885. };
  70886. }
  70887. catch (ex) {
  70888. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  70889. callback(-1);
  70890. }
  70891. }
  70892. else {
  70893. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70894. callback(-1);
  70895. }
  70896. };
  70897. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  70898. var _this = this;
  70899. if (this.isSupported && !this.hasReachedQuota && this.db) {
  70900. try {
  70901. // Open a transaction to the database
  70902. var transaction = this.db.transaction(["versions"], "readwrite");
  70903. // the transaction could abort because of a QuotaExceededError error
  70904. transaction.onabort = function (event) {
  70905. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70906. var error = event.srcElement['error'];
  70907. if (error && error.name === "QuotaExceededError") {
  70908. _this.hasReachedQuota = true;
  70909. }
  70910. }
  70911. catch (ex) { }
  70912. callback(-1);
  70913. };
  70914. transaction.oncomplete = function (event) {
  70915. callback(_this.manifestVersionFound);
  70916. };
  70917. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  70918. // Put the scene into the database
  70919. var addRequest = transaction.objectStore("versions").put(newVersion);
  70920. addRequest.onsuccess = function (event) {
  70921. };
  70922. addRequest.onerror = function (event) {
  70923. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  70924. };
  70925. }
  70926. catch (ex) {
  70927. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  70928. callback(-1);
  70929. }
  70930. }
  70931. else {
  70932. callback(-1);
  70933. }
  70934. };
  70935. /**
  70936. * Loads a file from database
  70937. * @param url defines the URL to load from
  70938. * @param sceneLoaded defines a callback to call on success
  70939. * @param progressCallBack defines a callback to call when progress changed
  70940. * @param errorCallback defines a callback to call on error
  70941. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  70942. */
  70943. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  70944. var _this = this;
  70945. var completeUrl = Database._ReturnFullUrlLocation(url);
  70946. var saveAndLoadFile = function () {
  70947. // the scene is not yet in the DB, let's try to save it
  70948. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70949. };
  70950. this._checkVersionFromDB(completeUrl, function (version) {
  70951. if (version !== -1) {
  70952. if (!_this.mustUpdateRessources) {
  70953. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  70954. }
  70955. else {
  70956. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70957. }
  70958. }
  70959. else {
  70960. if (errorCallback) {
  70961. errorCallback();
  70962. }
  70963. }
  70964. });
  70965. };
  70966. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  70967. if (this.isSupported && this.db) {
  70968. var targetStore;
  70969. if (url.indexOf(".babylon") !== -1) {
  70970. targetStore = "scenes";
  70971. }
  70972. else {
  70973. targetStore = "textures";
  70974. }
  70975. var file;
  70976. var transaction = this.db.transaction([targetStore]);
  70977. transaction.oncomplete = function (event) {
  70978. if (file) {
  70979. callback(file.data);
  70980. }
  70981. // file was not found in DB
  70982. else {
  70983. notInDBCallback();
  70984. }
  70985. };
  70986. transaction.onabort = function (event) {
  70987. notInDBCallback();
  70988. };
  70989. var getRequest = transaction.objectStore(targetStore).get(url);
  70990. getRequest.onsuccess = function (event) {
  70991. file = (event.target).result;
  70992. };
  70993. getRequest.onerror = function (event) {
  70994. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  70995. notInDBCallback();
  70996. };
  70997. }
  70998. else {
  70999. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71000. callback();
  71001. }
  71002. };
  71003. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  71004. var _this = this;
  71005. if (this.isSupported) {
  71006. var targetStore;
  71007. if (url.indexOf(".babylon") !== -1) {
  71008. targetStore = "scenes";
  71009. }
  71010. else {
  71011. targetStore = "textures";
  71012. }
  71013. // Create XHR
  71014. var xhr = new XMLHttpRequest();
  71015. var fileData;
  71016. xhr.open("GET", url, true);
  71017. if (useArrayBuffer) {
  71018. xhr.responseType = "arraybuffer";
  71019. }
  71020. if (progressCallback) {
  71021. xhr.onprogress = progressCallback;
  71022. }
  71023. xhr.addEventListener("load", function () {
  71024. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  71025. // Blob as response (XHR2)
  71026. //fileData = xhr.responseText;
  71027. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  71028. if (!_this.hasReachedQuota && _this.db) {
  71029. // Open a transaction to the database
  71030. var transaction = _this.db.transaction([targetStore], "readwrite");
  71031. // the transaction could abort because of a QuotaExceededError error
  71032. transaction.onabort = function (event) {
  71033. try {
  71034. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71035. var error = event.srcElement['error'];
  71036. if (error && error.name === "QuotaExceededError") {
  71037. _this.hasReachedQuota = true;
  71038. }
  71039. }
  71040. catch (ex) { }
  71041. callback(fileData);
  71042. };
  71043. transaction.oncomplete = function (event) {
  71044. callback(fileData);
  71045. };
  71046. var newFile;
  71047. if (targetStore === "scenes") {
  71048. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  71049. }
  71050. else {
  71051. newFile = { textureUrl: url, data: fileData };
  71052. }
  71053. try {
  71054. // Put the scene into the database
  71055. var addRequest = transaction.objectStore(targetStore).put(newFile);
  71056. addRequest.onsuccess = function (event) {
  71057. };
  71058. addRequest.onerror = function (event) {
  71059. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  71060. };
  71061. }
  71062. catch (ex) {
  71063. callback(fileData);
  71064. }
  71065. }
  71066. else {
  71067. callback(fileData);
  71068. }
  71069. }
  71070. else {
  71071. if (xhr.status >= 400 && errorCallback) {
  71072. errorCallback(xhr);
  71073. }
  71074. else {
  71075. callback();
  71076. }
  71077. }
  71078. }, false);
  71079. xhr.addEventListener("error", function (event) {
  71080. BABYLON.Tools.Error("error on XHR request.");
  71081. callback();
  71082. }, false);
  71083. xhr.send();
  71084. }
  71085. else {
  71086. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71087. callback();
  71088. }
  71089. };
  71090. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  71091. Database.IsUASupportingBlobStorage = true;
  71092. /** Gets a boolean indicating if Database storate is enabled */
  71093. Database.IDBStorageEnabled = true;
  71094. Database._ParseURL = function (url) {
  71095. var a = document.createElement('a');
  71096. a.href = url;
  71097. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  71098. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  71099. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  71100. return absLocation;
  71101. };
  71102. Database._ReturnFullUrlLocation = function (url) {
  71103. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  71104. return (Database._ParseURL(window.location.href) + url);
  71105. }
  71106. else {
  71107. return url;
  71108. }
  71109. };
  71110. return Database;
  71111. }());
  71112. BABYLON.Database = Database;
  71113. })(BABYLON || (BABYLON = {}));
  71114. //# sourceMappingURL=babylon.database.js.map
  71115. var BABYLON;
  71116. (function (BABYLON) {
  71117. var FresnelParameters = /** @class */ (function () {
  71118. function FresnelParameters() {
  71119. this._isEnabled = true;
  71120. this.leftColor = BABYLON.Color3.White();
  71121. this.rightColor = BABYLON.Color3.Black();
  71122. this.bias = 0;
  71123. this.power = 1;
  71124. }
  71125. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  71126. get: function () {
  71127. return this._isEnabled;
  71128. },
  71129. set: function (value) {
  71130. if (this._isEnabled === value) {
  71131. return;
  71132. }
  71133. this._isEnabled = value;
  71134. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  71135. },
  71136. enumerable: true,
  71137. configurable: true
  71138. });
  71139. FresnelParameters.prototype.clone = function () {
  71140. var newFresnelParameters = new FresnelParameters();
  71141. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  71142. return newFresnelParameters;
  71143. };
  71144. FresnelParameters.prototype.serialize = function () {
  71145. var serializationObject = {};
  71146. serializationObject.isEnabled = this.isEnabled;
  71147. serializationObject.leftColor = this.leftColor.asArray();
  71148. serializationObject.rightColor = this.rightColor.asArray();
  71149. serializationObject.bias = this.bias;
  71150. serializationObject.power = this.power;
  71151. return serializationObject;
  71152. };
  71153. FresnelParameters.Parse = function (parsedFresnelParameters) {
  71154. var fresnelParameters = new FresnelParameters();
  71155. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  71156. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  71157. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  71158. fresnelParameters.bias = parsedFresnelParameters.bias;
  71159. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  71160. return fresnelParameters;
  71161. };
  71162. return FresnelParameters;
  71163. }());
  71164. BABYLON.FresnelParameters = FresnelParameters;
  71165. })(BABYLON || (BABYLON = {}));
  71166. //# sourceMappingURL=babylon.fresnelParameters.js.map
  71167. var BABYLON;
  71168. (function (BABYLON) {
  71169. var MultiMaterial = /** @class */ (function (_super) {
  71170. __extends(MultiMaterial, _super);
  71171. function MultiMaterial(name, scene) {
  71172. var _this = _super.call(this, name, scene, true) || this;
  71173. scene.multiMaterials.push(_this);
  71174. _this.subMaterials = new Array();
  71175. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  71176. return _this;
  71177. }
  71178. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  71179. get: function () {
  71180. return this._subMaterials;
  71181. },
  71182. set: function (value) {
  71183. this._subMaterials = value;
  71184. this._hookArray(value);
  71185. },
  71186. enumerable: true,
  71187. configurable: true
  71188. });
  71189. MultiMaterial.prototype._hookArray = function (array) {
  71190. var _this = this;
  71191. var oldPush = array.push;
  71192. array.push = function () {
  71193. var items = [];
  71194. for (var _i = 0; _i < arguments.length; _i++) {
  71195. items[_i] = arguments[_i];
  71196. }
  71197. var result = oldPush.apply(array, items);
  71198. _this._markAllSubMeshesAsTexturesDirty();
  71199. return result;
  71200. };
  71201. var oldSplice = array.splice;
  71202. array.splice = function (index, deleteCount) {
  71203. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71204. _this._markAllSubMeshesAsTexturesDirty();
  71205. return deleted;
  71206. };
  71207. };
  71208. // Properties
  71209. MultiMaterial.prototype.getSubMaterial = function (index) {
  71210. if (index < 0 || index >= this.subMaterials.length) {
  71211. return this.getScene().defaultMaterial;
  71212. }
  71213. return this.subMaterials[index];
  71214. };
  71215. MultiMaterial.prototype.getActiveTextures = function () {
  71216. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  71217. if (subMaterial) {
  71218. return subMaterial.getActiveTextures();
  71219. }
  71220. else {
  71221. return [];
  71222. }
  71223. }));
  71224. var _a;
  71225. };
  71226. // Methods
  71227. MultiMaterial.prototype.getClassName = function () {
  71228. return "MultiMaterial";
  71229. };
  71230. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71231. for (var index = 0; index < this.subMaterials.length; index++) {
  71232. var subMaterial = this.subMaterials[index];
  71233. if (subMaterial) {
  71234. if (subMaterial.storeEffectOnSubMeshes) {
  71235. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  71236. return false;
  71237. }
  71238. continue;
  71239. }
  71240. if (!subMaterial.isReady(mesh)) {
  71241. return false;
  71242. }
  71243. }
  71244. }
  71245. return true;
  71246. };
  71247. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  71248. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  71249. for (var index = 0; index < this.subMaterials.length; index++) {
  71250. var subMaterial = null;
  71251. var current = this.subMaterials[index];
  71252. if (cloneChildren && current) {
  71253. subMaterial = current.clone(name + "-" + current.name);
  71254. }
  71255. else {
  71256. subMaterial = this.subMaterials[index];
  71257. }
  71258. newMultiMaterial.subMaterials.push(subMaterial);
  71259. }
  71260. return newMultiMaterial;
  71261. };
  71262. MultiMaterial.prototype.serialize = function () {
  71263. var serializationObject = {};
  71264. serializationObject.name = this.name;
  71265. serializationObject.id = this.id;
  71266. if (BABYLON.Tags) {
  71267. serializationObject.tags = BABYLON.Tags.GetTags(this);
  71268. }
  71269. serializationObject.materials = [];
  71270. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  71271. var subMat = this.subMaterials[matIndex];
  71272. if (subMat) {
  71273. serializationObject.materials.push(subMat.id);
  71274. }
  71275. else {
  71276. serializationObject.materials.push(null);
  71277. }
  71278. }
  71279. return serializationObject;
  71280. };
  71281. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  71282. var scene = this.getScene();
  71283. if (!scene) {
  71284. return;
  71285. }
  71286. var index = scene.multiMaterials.indexOf(this);
  71287. if (index >= 0) {
  71288. scene.multiMaterials.splice(index, 1);
  71289. }
  71290. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  71291. };
  71292. return MultiMaterial;
  71293. }(BABYLON.Material));
  71294. BABYLON.MultiMaterial = MultiMaterial;
  71295. })(BABYLON || (BABYLON = {}));
  71296. //# sourceMappingURL=babylon.multiMaterial.js.map
  71297. var BABYLON;
  71298. (function (BABYLON) {
  71299. var FreeCameraTouchInput = /** @class */ (function () {
  71300. function FreeCameraTouchInput() {
  71301. this._offsetX = null;
  71302. this._offsetY = null;
  71303. this._pointerPressed = new Array();
  71304. this.touchAngularSensibility = 200000.0;
  71305. this.touchMoveSensibility = 250.0;
  71306. }
  71307. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  71308. var _this = this;
  71309. var previousPosition = null;
  71310. if (this._pointerInput === undefined) {
  71311. this._onLostFocus = function (evt) {
  71312. _this._offsetX = null;
  71313. _this._offsetY = null;
  71314. };
  71315. this._pointerInput = function (p, s) {
  71316. var evt = p.event;
  71317. if (evt.pointerType === "mouse") {
  71318. return;
  71319. }
  71320. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71321. if (!noPreventDefault) {
  71322. evt.preventDefault();
  71323. }
  71324. _this._pointerPressed.push(evt.pointerId);
  71325. if (_this._pointerPressed.length !== 1) {
  71326. return;
  71327. }
  71328. previousPosition = {
  71329. x: evt.clientX,
  71330. y: evt.clientY
  71331. };
  71332. }
  71333. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  71334. if (!noPreventDefault) {
  71335. evt.preventDefault();
  71336. }
  71337. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71338. if (index === -1) {
  71339. return;
  71340. }
  71341. _this._pointerPressed.splice(index, 1);
  71342. if (index != 0) {
  71343. return;
  71344. }
  71345. previousPosition = null;
  71346. _this._offsetX = null;
  71347. _this._offsetY = null;
  71348. }
  71349. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  71350. if (!noPreventDefault) {
  71351. evt.preventDefault();
  71352. }
  71353. if (!previousPosition) {
  71354. return;
  71355. }
  71356. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71357. if (index != 0) {
  71358. return;
  71359. }
  71360. _this._offsetX = evt.clientX - previousPosition.x;
  71361. _this._offsetY = -(evt.clientY - previousPosition.y);
  71362. }
  71363. };
  71364. }
  71365. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  71366. if (this._onLostFocus) {
  71367. element.addEventListener("blur", this._onLostFocus);
  71368. }
  71369. };
  71370. FreeCameraTouchInput.prototype.detachControl = function (element) {
  71371. if (this._pointerInput && element) {
  71372. if (this._observer) {
  71373. this.camera.getScene().onPointerObservable.remove(this._observer);
  71374. this._observer = null;
  71375. }
  71376. if (this._onLostFocus) {
  71377. element.removeEventListener("blur", this._onLostFocus);
  71378. this._onLostFocus = null;
  71379. }
  71380. this._pointerPressed = [];
  71381. this._offsetX = null;
  71382. this._offsetY = null;
  71383. }
  71384. };
  71385. FreeCameraTouchInput.prototype.checkInputs = function () {
  71386. if (this._offsetX && this._offsetY) {
  71387. var camera = this.camera;
  71388. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  71389. if (this._pointerPressed.length > 1) {
  71390. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  71391. }
  71392. else {
  71393. var speed = camera._computeLocalCameraSpeed();
  71394. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  71395. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  71396. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  71397. }
  71398. }
  71399. };
  71400. FreeCameraTouchInput.prototype.getClassName = function () {
  71401. return "FreeCameraTouchInput";
  71402. };
  71403. FreeCameraTouchInput.prototype.getSimpleName = function () {
  71404. return "touch";
  71405. };
  71406. __decorate([
  71407. BABYLON.serialize()
  71408. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  71409. __decorate([
  71410. BABYLON.serialize()
  71411. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  71412. return FreeCameraTouchInput;
  71413. }());
  71414. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  71415. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  71416. })(BABYLON || (BABYLON = {}));
  71417. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  71418. var BABYLON;
  71419. (function (BABYLON) {
  71420. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  71421. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  71422. });
  71423. // We're mainly based on the logic defined into the FreeCamera code
  71424. var TouchCamera = /** @class */ (function (_super) {
  71425. __extends(TouchCamera, _super);
  71426. //-- end properties for backward compatibility for inputs
  71427. function TouchCamera(name, position, scene) {
  71428. var _this = _super.call(this, name, position, scene) || this;
  71429. _this.inputs.addTouch();
  71430. _this._setupInputs();
  71431. return _this;
  71432. }
  71433. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  71434. //-- Begin properties for backward compatibility for inputs
  71435. get: function () {
  71436. var touch = this.inputs.attached["touch"];
  71437. if (touch)
  71438. return touch.touchAngularSensibility;
  71439. return 0;
  71440. },
  71441. set: function (value) {
  71442. var touch = this.inputs.attached["touch"];
  71443. if (touch)
  71444. touch.touchAngularSensibility = value;
  71445. },
  71446. enumerable: true,
  71447. configurable: true
  71448. });
  71449. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  71450. get: function () {
  71451. var touch = this.inputs.attached["touch"];
  71452. if (touch)
  71453. return touch.touchMoveSensibility;
  71454. return 0;
  71455. },
  71456. set: function (value) {
  71457. var touch = this.inputs.attached["touch"];
  71458. if (touch)
  71459. touch.touchMoveSensibility = value;
  71460. },
  71461. enumerable: true,
  71462. configurable: true
  71463. });
  71464. TouchCamera.prototype.getClassName = function () {
  71465. return "TouchCamera";
  71466. };
  71467. TouchCamera.prototype._setupInputs = function () {
  71468. var mouse = this.inputs.attached["mouse"];
  71469. if (mouse) {
  71470. mouse.touchEnabled = false;
  71471. }
  71472. };
  71473. return TouchCamera;
  71474. }(BABYLON.FreeCamera));
  71475. BABYLON.TouchCamera = TouchCamera;
  71476. })(BABYLON || (BABYLON = {}));
  71477. //# sourceMappingURL=babylon.touchCamera.js.map
  71478. var BABYLON;
  71479. (function (BABYLON) {
  71480. var ProceduralTexture = /** @class */ (function (_super) {
  71481. __extends(ProceduralTexture, _super);
  71482. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  71483. if (fallbackTexture === void 0) { fallbackTexture = null; }
  71484. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71485. if (isCube === void 0) { isCube = false; }
  71486. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71487. _this.isCube = isCube;
  71488. _this.isEnabled = true;
  71489. _this._currentRefreshId = -1;
  71490. _this._refreshRate = 1;
  71491. _this._vertexBuffers = {};
  71492. _this._uniforms = new Array();
  71493. _this._samplers = new Array();
  71494. _this._textures = {};
  71495. _this._floats = {};
  71496. _this._ints = {};
  71497. _this._floatsArrays = {};
  71498. _this._colors3 = {};
  71499. _this._colors4 = {};
  71500. _this._vectors2 = {};
  71501. _this._vectors3 = {};
  71502. _this._matrices = {};
  71503. _this._fallbackTextureUsed = false;
  71504. scene = _this.getScene();
  71505. scene.proceduralTextures.push(_this);
  71506. _this._engine = scene.getEngine();
  71507. _this.name = name;
  71508. _this.isRenderTarget = true;
  71509. _this._size = size;
  71510. _this._generateMipMaps = generateMipMaps;
  71511. _this.setFragment(fragment);
  71512. _this._fallbackTexture = fallbackTexture;
  71513. if (isCube) {
  71514. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  71515. _this.setFloat("face", 0);
  71516. }
  71517. else {
  71518. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  71519. }
  71520. // VBO
  71521. var vertices = [];
  71522. vertices.push(1, 1);
  71523. vertices.push(-1, 1);
  71524. vertices.push(-1, -1);
  71525. vertices.push(1, -1);
  71526. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71527. _this._createIndexBuffer();
  71528. return _this;
  71529. }
  71530. ProceduralTexture.prototype._createIndexBuffer = function () {
  71531. var engine = this._engine;
  71532. // Indices
  71533. var indices = [];
  71534. indices.push(0);
  71535. indices.push(1);
  71536. indices.push(2);
  71537. indices.push(0);
  71538. indices.push(2);
  71539. indices.push(3);
  71540. this._indexBuffer = engine.createIndexBuffer(indices);
  71541. };
  71542. ProceduralTexture.prototype._rebuild = function () {
  71543. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71544. if (vb) {
  71545. vb._rebuild();
  71546. }
  71547. this._createIndexBuffer();
  71548. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71549. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71550. }
  71551. };
  71552. ProceduralTexture.prototype.reset = function () {
  71553. if (this._effect === undefined) {
  71554. return;
  71555. }
  71556. var engine = this._engine;
  71557. engine._releaseEffect(this._effect);
  71558. };
  71559. ProceduralTexture.prototype.isReady = function () {
  71560. var _this = this;
  71561. var engine = this._engine;
  71562. var shaders;
  71563. if (!this._fragment) {
  71564. return false;
  71565. }
  71566. if (this._fallbackTextureUsed) {
  71567. return true;
  71568. }
  71569. if (this._fragment.fragmentElement !== undefined) {
  71570. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  71571. }
  71572. else {
  71573. shaders = { vertex: "procedural", fragment: this._fragment };
  71574. }
  71575. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  71576. _this.releaseInternalTexture();
  71577. if (_this._fallbackTexture) {
  71578. _this._texture = _this._fallbackTexture._texture;
  71579. if (_this._texture) {
  71580. _this._texture.incrementReferences();
  71581. }
  71582. }
  71583. _this._fallbackTextureUsed = true;
  71584. });
  71585. return this._effect.isReady();
  71586. };
  71587. ProceduralTexture.prototype.resetRefreshCounter = function () {
  71588. this._currentRefreshId = -1;
  71589. };
  71590. ProceduralTexture.prototype.setFragment = function (fragment) {
  71591. this._fragment = fragment;
  71592. };
  71593. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  71594. get: function () {
  71595. return this._refreshRate;
  71596. },
  71597. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71598. set: function (value) {
  71599. this._refreshRate = value;
  71600. this.resetRefreshCounter();
  71601. },
  71602. enumerable: true,
  71603. configurable: true
  71604. });
  71605. ProceduralTexture.prototype._shouldRender = function () {
  71606. if (!this.isEnabled || !this.isReady() || !this._texture) {
  71607. return false;
  71608. }
  71609. if (this._fallbackTextureUsed) {
  71610. return false;
  71611. }
  71612. if (this._currentRefreshId === -1) { // At least render once
  71613. this._currentRefreshId = 1;
  71614. return true;
  71615. }
  71616. if (this.refreshRate === this._currentRefreshId) {
  71617. this._currentRefreshId = 1;
  71618. return true;
  71619. }
  71620. this._currentRefreshId++;
  71621. return false;
  71622. };
  71623. ProceduralTexture.prototype.getRenderSize = function () {
  71624. return this._size;
  71625. };
  71626. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  71627. if (this._fallbackTextureUsed) {
  71628. return;
  71629. }
  71630. this.releaseInternalTexture();
  71631. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  71632. // Update properties
  71633. this._size = size;
  71634. this._generateMipMaps = generateMipMaps;
  71635. };
  71636. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  71637. if (this._uniforms.indexOf(uniformName) === -1) {
  71638. this._uniforms.push(uniformName);
  71639. }
  71640. };
  71641. ProceduralTexture.prototype.setTexture = function (name, texture) {
  71642. if (this._samplers.indexOf(name) === -1) {
  71643. this._samplers.push(name);
  71644. }
  71645. this._textures[name] = texture;
  71646. return this;
  71647. };
  71648. ProceduralTexture.prototype.setFloat = function (name, value) {
  71649. this._checkUniform(name);
  71650. this._floats[name] = value;
  71651. return this;
  71652. };
  71653. /**
  71654. * Set the value of an uniform to an integer value
  71655. * @param name defines the name of the uniform
  71656. * @param value defines the value to set
  71657. * @returns the current procedural texture
  71658. */
  71659. ProceduralTexture.prototype.setInt = function (name, value) {
  71660. this._checkUniform(name);
  71661. this._ints[name] = value;
  71662. return this;
  71663. };
  71664. ProceduralTexture.prototype.setFloats = function (name, value) {
  71665. this._checkUniform(name);
  71666. this._floatsArrays[name] = value;
  71667. return this;
  71668. };
  71669. ProceduralTexture.prototype.setColor3 = function (name, value) {
  71670. this._checkUniform(name);
  71671. this._colors3[name] = value;
  71672. return this;
  71673. };
  71674. ProceduralTexture.prototype.setColor4 = function (name, value) {
  71675. this._checkUniform(name);
  71676. this._colors4[name] = value;
  71677. return this;
  71678. };
  71679. ProceduralTexture.prototype.setVector2 = function (name, value) {
  71680. this._checkUniform(name);
  71681. this._vectors2[name] = value;
  71682. return this;
  71683. };
  71684. ProceduralTexture.prototype.setVector3 = function (name, value) {
  71685. this._checkUniform(name);
  71686. this._vectors3[name] = value;
  71687. return this;
  71688. };
  71689. ProceduralTexture.prototype.setMatrix = function (name, value) {
  71690. this._checkUniform(name);
  71691. this._matrices[name] = value;
  71692. return this;
  71693. };
  71694. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71695. var scene = this.getScene();
  71696. if (!scene) {
  71697. return;
  71698. }
  71699. var engine = this._engine;
  71700. // Render
  71701. engine.enableEffect(this._effect);
  71702. engine.setState(false);
  71703. // Texture
  71704. for (var name in this._textures) {
  71705. this._effect.setTexture(name, this._textures[name]);
  71706. }
  71707. // Float
  71708. for (name in this._ints) {
  71709. this._effect.setInt(name, this._ints[name]);
  71710. }
  71711. // Float
  71712. for (name in this._floats) {
  71713. this._effect.setFloat(name, this._floats[name]);
  71714. }
  71715. // Floats
  71716. for (name in this._floatsArrays) {
  71717. this._effect.setArray(name, this._floatsArrays[name]);
  71718. }
  71719. // Color3
  71720. for (name in this._colors3) {
  71721. this._effect.setColor3(name, this._colors3[name]);
  71722. }
  71723. // Color4
  71724. for (name in this._colors4) {
  71725. var color = this._colors4[name];
  71726. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  71727. }
  71728. // Vector2
  71729. for (name in this._vectors2) {
  71730. this._effect.setVector2(name, this._vectors2[name]);
  71731. }
  71732. // Vector3
  71733. for (name in this._vectors3) {
  71734. this._effect.setVector3(name, this._vectors3[name]);
  71735. }
  71736. // Matrix
  71737. for (name in this._matrices) {
  71738. this._effect.setMatrix(name, this._matrices[name]);
  71739. }
  71740. if (!this._texture) {
  71741. return;
  71742. }
  71743. if (this.isCube) {
  71744. for (var face = 0; face < 6; face++) {
  71745. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  71746. // VBOs
  71747. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71748. this._effect.setFloat("face", face);
  71749. // Clear
  71750. engine.clear(scene.clearColor, true, true, true);
  71751. // Draw order
  71752. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71753. // Mipmaps
  71754. if (face === 5) {
  71755. engine.generateMipMapsForCubemap(this._texture);
  71756. }
  71757. }
  71758. }
  71759. else {
  71760. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  71761. // VBOs
  71762. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71763. // Clear
  71764. engine.clear(scene.clearColor, true, true, true);
  71765. // Draw order
  71766. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71767. }
  71768. // Unbind
  71769. engine.unBindFramebuffer(this._texture, this.isCube);
  71770. if (this.onGenerated) {
  71771. this.onGenerated();
  71772. }
  71773. };
  71774. ProceduralTexture.prototype.clone = function () {
  71775. var textureSize = this.getSize();
  71776. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  71777. // Base texture
  71778. newTexture.hasAlpha = this.hasAlpha;
  71779. newTexture.level = this.level;
  71780. // RenderTarget Texture
  71781. newTexture.coordinatesMode = this.coordinatesMode;
  71782. return newTexture;
  71783. };
  71784. ProceduralTexture.prototype.dispose = function () {
  71785. var scene = this.getScene();
  71786. if (!scene) {
  71787. return;
  71788. }
  71789. var index = scene.proceduralTextures.indexOf(this);
  71790. if (index >= 0) {
  71791. scene.proceduralTextures.splice(index, 1);
  71792. }
  71793. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71794. if (vertexBuffer) {
  71795. vertexBuffer.dispose();
  71796. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71797. }
  71798. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  71799. this._indexBuffer = null;
  71800. }
  71801. _super.prototype.dispose.call(this);
  71802. };
  71803. __decorate([
  71804. BABYLON.serialize()
  71805. ], ProceduralTexture.prototype, "_size", void 0);
  71806. __decorate([
  71807. BABYLON.serialize()
  71808. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  71809. __decorate([
  71810. BABYLON.serialize()
  71811. ], ProceduralTexture.prototype, "isEnabled", void 0);
  71812. __decorate([
  71813. BABYLON.serialize()
  71814. ], ProceduralTexture.prototype, "refreshRate", null);
  71815. return ProceduralTexture;
  71816. }(BABYLON.Texture));
  71817. BABYLON.ProceduralTexture = ProceduralTexture;
  71818. })(BABYLON || (BABYLON = {}));
  71819. //# sourceMappingURL=babylon.proceduralTexture.js.map
  71820. var BABYLON;
  71821. (function (BABYLON) {
  71822. var CustomProceduralTexture = /** @class */ (function (_super) {
  71823. __extends(CustomProceduralTexture, _super);
  71824. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  71825. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  71826. _this._animate = true;
  71827. _this._time = 0;
  71828. _this._texturePath = texturePath;
  71829. //Try to load json
  71830. _this.loadJson(texturePath);
  71831. _this.refreshRate = 1;
  71832. return _this;
  71833. }
  71834. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  71835. var _this = this;
  71836. var noConfigFile = function () {
  71837. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  71838. try {
  71839. _this.setFragment(_this._texturePath);
  71840. }
  71841. catch (ex) {
  71842. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  71843. }
  71844. };
  71845. var configFileUrl = jsonUrl + "/config.json";
  71846. var xhr = new XMLHttpRequest();
  71847. xhr.open("GET", configFileUrl, true);
  71848. xhr.addEventListener("load", function () {
  71849. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71850. try {
  71851. _this._config = JSON.parse(xhr.response);
  71852. _this.updateShaderUniforms();
  71853. _this.updateTextures();
  71854. _this.setFragment(_this._texturePath + "/custom");
  71855. _this._animate = _this._config.animate;
  71856. _this.refreshRate = _this._config.refreshrate;
  71857. }
  71858. catch (ex) {
  71859. noConfigFile();
  71860. }
  71861. }
  71862. else {
  71863. noConfigFile();
  71864. }
  71865. }, false);
  71866. xhr.addEventListener("error", function () {
  71867. noConfigFile();
  71868. }, false);
  71869. try {
  71870. xhr.send();
  71871. }
  71872. catch (ex) {
  71873. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  71874. }
  71875. };
  71876. CustomProceduralTexture.prototype.isReady = function () {
  71877. if (!_super.prototype.isReady.call(this)) {
  71878. return false;
  71879. }
  71880. for (var name in this._textures) {
  71881. var texture = this._textures[name];
  71882. if (!texture.isReady()) {
  71883. return false;
  71884. }
  71885. }
  71886. return true;
  71887. };
  71888. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71889. var scene = this.getScene();
  71890. if (this._animate && scene) {
  71891. this._time += scene.getAnimationRatio() * 0.03;
  71892. this.updateShaderUniforms();
  71893. }
  71894. _super.prototype.render.call(this, useCameraPostProcess);
  71895. };
  71896. CustomProceduralTexture.prototype.updateTextures = function () {
  71897. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  71898. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  71899. }
  71900. };
  71901. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  71902. if (this._config) {
  71903. for (var j = 0; j < this._config.uniforms.length; j++) {
  71904. var uniform = this._config.uniforms[j];
  71905. switch (uniform.type) {
  71906. case "float":
  71907. this.setFloat(uniform.name, uniform.value);
  71908. break;
  71909. case "color3":
  71910. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  71911. break;
  71912. case "color4":
  71913. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  71914. break;
  71915. case "vector2":
  71916. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  71917. break;
  71918. case "vector3":
  71919. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  71920. break;
  71921. }
  71922. }
  71923. }
  71924. this.setFloat("time", this._time);
  71925. };
  71926. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  71927. get: function () {
  71928. return this._animate;
  71929. },
  71930. set: function (value) {
  71931. this._animate = value;
  71932. },
  71933. enumerable: true,
  71934. configurable: true
  71935. });
  71936. return CustomProceduralTexture;
  71937. }(BABYLON.ProceduralTexture));
  71938. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  71939. })(BABYLON || (BABYLON = {}));
  71940. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  71941. var BABYLON;
  71942. (function (BABYLON) {
  71943. var FreeCameraGamepadInput = /** @class */ (function () {
  71944. function FreeCameraGamepadInput() {
  71945. this.gamepadAngularSensibility = 200;
  71946. this.gamepadMoveSensibility = 40;
  71947. // private members
  71948. this._cameraTransform = BABYLON.Matrix.Identity();
  71949. this._deltaTransform = BABYLON.Vector3.Zero();
  71950. this._vector3 = BABYLON.Vector3.Zero();
  71951. this._vector2 = BABYLON.Vector2.Zero();
  71952. }
  71953. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71954. var _this = this;
  71955. var manager = this.camera.getScene().gamepadManager;
  71956. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71957. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71958. // prioritize XBOX gamepads.
  71959. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71960. _this.gamepad = gamepad;
  71961. }
  71962. }
  71963. });
  71964. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71965. if (_this.gamepad === gamepad) {
  71966. _this.gamepad = null;
  71967. }
  71968. });
  71969. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71970. };
  71971. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  71972. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71973. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71974. this.gamepad = null;
  71975. };
  71976. FreeCameraGamepadInput.prototype.checkInputs = function () {
  71977. if (this.gamepad && this.gamepad.leftStick) {
  71978. var camera = this.camera;
  71979. var LSValues = this.gamepad.leftStick;
  71980. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  71981. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71982. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  71983. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  71984. var RSValues = this.gamepad.rightStick;
  71985. if (RSValues) {
  71986. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  71987. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  71988. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  71989. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  71990. }
  71991. else {
  71992. RSValues = { x: 0, y: 0 };
  71993. }
  71994. if (!camera.rotationQuaternion) {
  71995. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  71996. }
  71997. else {
  71998. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  71999. }
  72000. var speed = camera._computeLocalCameraSpeed() * 50.0;
  72001. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  72002. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  72003. camera.cameraDirection.addInPlace(this._deltaTransform);
  72004. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  72005. camera.cameraRotation.addInPlace(this._vector2);
  72006. }
  72007. };
  72008. FreeCameraGamepadInput.prototype.getClassName = function () {
  72009. return "FreeCameraGamepadInput";
  72010. };
  72011. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  72012. return "gamepad";
  72013. };
  72014. __decorate([
  72015. BABYLON.serialize()
  72016. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  72017. __decorate([
  72018. BABYLON.serialize()
  72019. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72020. return FreeCameraGamepadInput;
  72021. }());
  72022. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  72023. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  72024. })(BABYLON || (BABYLON = {}));
  72025. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  72026. var BABYLON;
  72027. (function (BABYLON) {
  72028. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  72029. function ArcRotateCameraGamepadInput() {
  72030. this.gamepadRotationSensibility = 80;
  72031. this.gamepadMoveSensibility = 40;
  72032. }
  72033. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72034. var _this = this;
  72035. var manager = this.camera.getScene().gamepadManager;
  72036. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72037. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72038. // prioritize XBOX gamepads.
  72039. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72040. _this.gamepad = gamepad;
  72041. }
  72042. }
  72043. });
  72044. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72045. if (_this.gamepad === gamepad) {
  72046. _this.gamepad = null;
  72047. }
  72048. });
  72049. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72050. };
  72051. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  72052. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72053. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72054. this.gamepad = null;
  72055. };
  72056. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  72057. if (this.gamepad) {
  72058. var camera = this.camera;
  72059. var RSValues = this.gamepad.rightStick;
  72060. if (RSValues) {
  72061. if (RSValues.x != 0) {
  72062. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  72063. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  72064. camera.inertialAlphaOffset += normalizedRX;
  72065. }
  72066. }
  72067. if (RSValues.y != 0) {
  72068. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  72069. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  72070. camera.inertialBetaOffset += normalizedRY;
  72071. }
  72072. }
  72073. }
  72074. var LSValues = this.gamepad.leftStick;
  72075. if (LSValues && LSValues.y != 0) {
  72076. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72077. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  72078. this.camera.inertialRadiusOffset -= normalizedLY;
  72079. }
  72080. }
  72081. }
  72082. };
  72083. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  72084. return "ArcRotateCameraGamepadInput";
  72085. };
  72086. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  72087. return "gamepad";
  72088. };
  72089. __decorate([
  72090. BABYLON.serialize()
  72091. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  72092. __decorate([
  72093. BABYLON.serialize()
  72094. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72095. return ArcRotateCameraGamepadInput;
  72096. }());
  72097. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  72098. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  72099. })(BABYLON || (BABYLON = {}));
  72100. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  72101. var BABYLON;
  72102. (function (BABYLON) {
  72103. var GamepadManager = /** @class */ (function () {
  72104. function GamepadManager(_scene) {
  72105. var _this = this;
  72106. this._scene = _scene;
  72107. this._babylonGamepads = [];
  72108. this._oneGamepadConnected = false;
  72109. this._isMonitoring = false;
  72110. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  72111. if (!BABYLON.Tools.IsWindowObjectExist()) {
  72112. this._gamepadEventSupported = false;
  72113. }
  72114. else {
  72115. this._gamepadEventSupported = 'GamepadEvent' in window;
  72116. this._gamepadSupport = (navigator.getGamepads ||
  72117. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  72118. }
  72119. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  72120. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  72121. for (var i in _this._babylonGamepads) {
  72122. var gamepad = _this._babylonGamepads[i];
  72123. if (gamepad && gamepad._isConnected) {
  72124. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  72125. }
  72126. }
  72127. });
  72128. this._onGamepadConnectedEvent = function (evt) {
  72129. var gamepad = evt.gamepad;
  72130. if (gamepad.index in _this._babylonGamepads) {
  72131. if (_this._babylonGamepads[gamepad.index].isConnected) {
  72132. return;
  72133. }
  72134. }
  72135. var newGamepad;
  72136. if (_this._babylonGamepads[gamepad.index]) {
  72137. newGamepad = _this._babylonGamepads[gamepad.index];
  72138. newGamepad.browserGamepad = gamepad;
  72139. newGamepad._isConnected = true;
  72140. }
  72141. else {
  72142. newGamepad = _this._addNewGamepad(gamepad);
  72143. }
  72144. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72145. _this._startMonitoringGamepads();
  72146. };
  72147. this._onGamepadDisconnectedEvent = function (evt) {
  72148. var gamepad = evt.gamepad;
  72149. // Remove the gamepad from the list of gamepads to monitor.
  72150. for (var i in _this._babylonGamepads) {
  72151. if (_this._babylonGamepads[i].index === gamepad.index) {
  72152. var disconnectedGamepad = _this._babylonGamepads[i];
  72153. disconnectedGamepad._isConnected = false;
  72154. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  72155. break;
  72156. }
  72157. }
  72158. };
  72159. if (this._gamepadSupport) {
  72160. //first add already-connected gamepads
  72161. this._updateGamepadObjects();
  72162. if (this._babylonGamepads.length) {
  72163. this._startMonitoringGamepads();
  72164. }
  72165. // Checking if the gamepad connected event is supported (like in Firefox)
  72166. if (this._gamepadEventSupported) {
  72167. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  72168. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  72169. }
  72170. else {
  72171. this._startMonitoringGamepads();
  72172. }
  72173. }
  72174. }
  72175. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  72176. get: function () {
  72177. return this._babylonGamepads;
  72178. },
  72179. enumerable: true,
  72180. configurable: true
  72181. });
  72182. GamepadManager.prototype.getGamepadByType = function (type) {
  72183. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  72184. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  72185. var gamepad = _a[_i];
  72186. if (gamepad && gamepad.type === type) {
  72187. return gamepad;
  72188. }
  72189. }
  72190. return null;
  72191. };
  72192. GamepadManager.prototype.dispose = function () {
  72193. if (this._gamepadEventSupported) {
  72194. if (this._onGamepadConnectedEvent) {
  72195. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  72196. }
  72197. if (this._onGamepadDisconnectedEvent) {
  72198. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  72199. }
  72200. this._onGamepadConnectedEvent = null;
  72201. this._onGamepadDisconnectedEvent = null;
  72202. }
  72203. this._babylonGamepads.forEach(function (gamepad) {
  72204. gamepad.dispose();
  72205. });
  72206. this.onGamepadConnectedObservable.clear();
  72207. this.onGamepadDisconnectedObservable.clear();
  72208. this._oneGamepadConnected = false;
  72209. this._stopMonitoringGamepads();
  72210. this._babylonGamepads = [];
  72211. };
  72212. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  72213. if (!this._oneGamepadConnected) {
  72214. this._oneGamepadConnected = true;
  72215. }
  72216. var newGamepad;
  72217. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  72218. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  72219. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  72220. }
  72221. // if pose is supported, use the (WebVR) pose enabled controller
  72222. else if (gamepad.pose) {
  72223. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  72224. }
  72225. else {
  72226. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  72227. }
  72228. this._babylonGamepads[newGamepad.index] = newGamepad;
  72229. return newGamepad;
  72230. };
  72231. GamepadManager.prototype._startMonitoringGamepads = function () {
  72232. if (!this._isMonitoring) {
  72233. this._isMonitoring = true;
  72234. //back-comp
  72235. if (!this._scene) {
  72236. this._checkGamepadsStatus();
  72237. }
  72238. }
  72239. };
  72240. GamepadManager.prototype._stopMonitoringGamepads = function () {
  72241. this._isMonitoring = false;
  72242. };
  72243. GamepadManager.prototype._checkGamepadsStatus = function () {
  72244. var _this = this;
  72245. // Hack to be compatible Chrome
  72246. this._updateGamepadObjects();
  72247. for (var i in this._babylonGamepads) {
  72248. var gamepad = this._babylonGamepads[i];
  72249. if (!gamepad || !gamepad.isConnected) {
  72250. continue;
  72251. }
  72252. gamepad.update();
  72253. }
  72254. if (this._isMonitoring && !this._scene) {
  72255. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  72256. }
  72257. };
  72258. // This function is called only on Chrome, which does not properly support
  72259. // connection/disconnection events and forces you to recopy again the gamepad object
  72260. GamepadManager.prototype._updateGamepadObjects = function () {
  72261. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  72262. for (var i = 0; i < gamepads.length; i++) {
  72263. var gamepad = gamepads[i];
  72264. if (gamepad) {
  72265. if (!this._babylonGamepads[gamepad.index]) {
  72266. var newGamepad = this._addNewGamepad(gamepad);
  72267. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72268. }
  72269. else {
  72270. // Forced to copy again this object for Chrome for unknown reason
  72271. this._babylonGamepads[i].browserGamepad = gamepad;
  72272. if (!this._babylonGamepads[i].isConnected) {
  72273. this._babylonGamepads[i]._isConnected = true;
  72274. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  72275. }
  72276. }
  72277. }
  72278. }
  72279. };
  72280. return GamepadManager;
  72281. }());
  72282. BABYLON.GamepadManager = GamepadManager;
  72283. })(BABYLON || (BABYLON = {}));
  72284. //# sourceMappingURL=babylon.gamepadManager.js.map
  72285. var BABYLON;
  72286. (function (BABYLON) {
  72287. var StickValues = /** @class */ (function () {
  72288. function StickValues(x, y) {
  72289. this.x = x;
  72290. this.y = y;
  72291. }
  72292. return StickValues;
  72293. }());
  72294. BABYLON.StickValues = StickValues;
  72295. var Gamepad = /** @class */ (function () {
  72296. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  72297. if (leftStickX === void 0) { leftStickX = 0; }
  72298. if (leftStickY === void 0) { leftStickY = 1; }
  72299. if (rightStickX === void 0) { rightStickX = 2; }
  72300. if (rightStickY === void 0) { rightStickY = 3; }
  72301. this.id = id;
  72302. this.index = index;
  72303. this.browserGamepad = browserGamepad;
  72304. this._isConnected = true;
  72305. this._invertLeftStickY = false;
  72306. this.type = Gamepad.GAMEPAD;
  72307. this._leftStickAxisX = leftStickX;
  72308. this._leftStickAxisY = leftStickY;
  72309. this._rightStickAxisX = rightStickX;
  72310. this._rightStickAxisY = rightStickY;
  72311. if (this.browserGamepad.axes.length >= 2) {
  72312. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72313. }
  72314. if (this.browserGamepad.axes.length >= 4) {
  72315. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72316. }
  72317. }
  72318. Object.defineProperty(Gamepad.prototype, "isConnected", {
  72319. get: function () {
  72320. return this._isConnected;
  72321. },
  72322. enumerable: true,
  72323. configurable: true
  72324. });
  72325. Gamepad.prototype.onleftstickchanged = function (callback) {
  72326. this._onleftstickchanged = callback;
  72327. };
  72328. Gamepad.prototype.onrightstickchanged = function (callback) {
  72329. this._onrightstickchanged = callback;
  72330. };
  72331. Object.defineProperty(Gamepad.prototype, "leftStick", {
  72332. get: function () {
  72333. return this._leftStick;
  72334. },
  72335. set: function (newValues) {
  72336. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  72337. this._onleftstickchanged(newValues);
  72338. }
  72339. this._leftStick = newValues;
  72340. },
  72341. enumerable: true,
  72342. configurable: true
  72343. });
  72344. Object.defineProperty(Gamepad.prototype, "rightStick", {
  72345. get: function () {
  72346. return this._rightStick;
  72347. },
  72348. set: function (newValues) {
  72349. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  72350. this._onrightstickchanged(newValues);
  72351. }
  72352. this._rightStick = newValues;
  72353. },
  72354. enumerable: true,
  72355. configurable: true
  72356. });
  72357. Gamepad.prototype.update = function () {
  72358. if (this._leftStick) {
  72359. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72360. if (this._invertLeftStickY) {
  72361. this.leftStick.y *= -1;
  72362. }
  72363. }
  72364. if (this._rightStick) {
  72365. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72366. }
  72367. };
  72368. Gamepad.prototype.dispose = function () {
  72369. };
  72370. Gamepad.GAMEPAD = 0;
  72371. Gamepad.GENERIC = 1;
  72372. Gamepad.XBOX = 2;
  72373. Gamepad.POSE_ENABLED = 3;
  72374. return Gamepad;
  72375. }());
  72376. BABYLON.Gamepad = Gamepad;
  72377. var GenericPad = /** @class */ (function (_super) {
  72378. __extends(GenericPad, _super);
  72379. function GenericPad(id, index, browserGamepad) {
  72380. var _this = _super.call(this, id, index, browserGamepad) || this;
  72381. _this.onButtonDownObservable = new BABYLON.Observable();
  72382. _this.onButtonUpObservable = new BABYLON.Observable();
  72383. _this.type = Gamepad.GENERIC;
  72384. _this._buttons = new Array(browserGamepad.buttons.length);
  72385. return _this;
  72386. }
  72387. GenericPad.prototype.onbuttondown = function (callback) {
  72388. this._onbuttondown = callback;
  72389. };
  72390. GenericPad.prototype.onbuttonup = function (callback) {
  72391. this._onbuttonup = callback;
  72392. };
  72393. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  72394. if (newValue !== currentValue) {
  72395. if (newValue === 1) {
  72396. if (this._onbuttondown) {
  72397. this._onbuttondown(buttonIndex);
  72398. }
  72399. this.onButtonDownObservable.notifyObservers(buttonIndex);
  72400. }
  72401. if (newValue === 0) {
  72402. if (this._onbuttonup) {
  72403. this._onbuttonup(buttonIndex);
  72404. }
  72405. this.onButtonUpObservable.notifyObservers(buttonIndex);
  72406. }
  72407. }
  72408. return newValue;
  72409. };
  72410. GenericPad.prototype.update = function () {
  72411. _super.prototype.update.call(this);
  72412. for (var index = 0; index < this._buttons.length; index++) {
  72413. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  72414. }
  72415. };
  72416. GenericPad.prototype.dispose = function () {
  72417. _super.prototype.dispose.call(this);
  72418. this.onButtonDownObservable.clear();
  72419. this.onButtonUpObservable.clear();
  72420. };
  72421. return GenericPad;
  72422. }(Gamepad));
  72423. BABYLON.GenericPad = GenericPad;
  72424. })(BABYLON || (BABYLON = {}));
  72425. //# sourceMappingURL=babylon.gamepad.js.map
  72426. var BABYLON;
  72427. (function (BABYLON) {
  72428. /**
  72429. * Defines supported buttons for XBox360 compatible gamepads
  72430. */
  72431. var Xbox360Button;
  72432. (function (Xbox360Button) {
  72433. /** A */
  72434. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  72435. /** B */
  72436. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  72437. /** X */
  72438. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  72439. /** Y */
  72440. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  72441. /** Start */
  72442. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  72443. /** Back */
  72444. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  72445. /** Left button */
  72446. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  72447. /** Right button */
  72448. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  72449. /** Left stick */
  72450. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  72451. /** Right stick */
  72452. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  72453. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  72454. /** Defines values for XBox360 DPad */
  72455. var Xbox360Dpad;
  72456. (function (Xbox360Dpad) {
  72457. /** Up */
  72458. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  72459. /** Down */
  72460. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  72461. /** Left */
  72462. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  72463. /** Right */
  72464. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  72465. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  72466. /**
  72467. * Defines a XBox360 gamepad
  72468. */
  72469. var Xbox360Pad = /** @class */ (function (_super) {
  72470. __extends(Xbox360Pad, _super);
  72471. /**
  72472. * Creates a new XBox360 gamepad object
  72473. * @param id defines the id of this gamepad
  72474. * @param index defines its index
  72475. * @param gamepad defines the internal HTML gamepad object
  72476. * @param xboxOne defines if it is a XBox One gamepad
  72477. */
  72478. function Xbox360Pad(id, index, gamepad, xboxOne) {
  72479. if (xboxOne === void 0) { xboxOne = false; }
  72480. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  72481. _this._leftTrigger = 0;
  72482. _this._rightTrigger = 0;
  72483. /** Observable raised when a button is pressed */
  72484. _this.onButtonDownObservable = new BABYLON.Observable();
  72485. /** Observable raised when a button is released */
  72486. _this.onButtonUpObservable = new BABYLON.Observable();
  72487. /** Observable raised when a pad is pressed */
  72488. _this.onPadDownObservable = new BABYLON.Observable();
  72489. /** Observable raised when a pad is released */
  72490. _this.onPadUpObservable = new BABYLON.Observable();
  72491. _this._buttonA = 0;
  72492. _this._buttonB = 0;
  72493. _this._buttonX = 0;
  72494. _this._buttonY = 0;
  72495. _this._buttonBack = 0;
  72496. _this._buttonStart = 0;
  72497. _this._buttonLB = 0;
  72498. _this._buttonRB = 0;
  72499. _this._buttonLeftStick = 0;
  72500. _this._buttonRightStick = 0;
  72501. _this._dPadUp = 0;
  72502. _this._dPadDown = 0;
  72503. _this._dPadLeft = 0;
  72504. _this._dPadRight = 0;
  72505. _this._isXboxOnePad = false;
  72506. _this.type = BABYLON.Gamepad.XBOX;
  72507. _this._isXboxOnePad = xboxOne;
  72508. return _this;
  72509. }
  72510. /**
  72511. * Defines the callback to call when left trigger is pressed
  72512. * @param callback defines the callback to use
  72513. */
  72514. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  72515. this._onlefttriggerchanged = callback;
  72516. };
  72517. /**
  72518. * Defines the callback to call when right trigger is pressed
  72519. * @param callback defines the callback to use
  72520. */
  72521. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  72522. this._onrighttriggerchanged = callback;
  72523. };
  72524. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  72525. /**
  72526. * Gets or sets left trigger value
  72527. */
  72528. get: function () {
  72529. return this._leftTrigger;
  72530. },
  72531. set: function (newValue) {
  72532. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  72533. this._onlefttriggerchanged(newValue);
  72534. }
  72535. this._leftTrigger = newValue;
  72536. },
  72537. enumerable: true,
  72538. configurable: true
  72539. });
  72540. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  72541. /**
  72542. * Gets or sets right trigger value
  72543. */
  72544. get: function () {
  72545. return this._rightTrigger;
  72546. },
  72547. set: function (newValue) {
  72548. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  72549. this._onrighttriggerchanged(newValue);
  72550. }
  72551. this._rightTrigger = newValue;
  72552. },
  72553. enumerable: true,
  72554. configurable: true
  72555. });
  72556. /**
  72557. * Defines the callback to call when a button is pressed
  72558. * @param callback defines the callback to use
  72559. */
  72560. Xbox360Pad.prototype.onbuttondown = function (callback) {
  72561. this._onbuttondown = callback;
  72562. };
  72563. /**
  72564. * Defines the callback to call when a button is released
  72565. * @param callback defines the callback to use
  72566. */
  72567. Xbox360Pad.prototype.onbuttonup = function (callback) {
  72568. this._onbuttonup = callback;
  72569. };
  72570. /**
  72571. * Defines the callback to call when a pad is pressed
  72572. * @param callback defines the callback to use
  72573. */
  72574. Xbox360Pad.prototype.ondpaddown = function (callback) {
  72575. this._ondpaddown = callback;
  72576. };
  72577. /**
  72578. * Defines the callback to call when a pad is released
  72579. * @param callback defines the callback to use
  72580. */
  72581. Xbox360Pad.prototype.ondpadup = function (callback) {
  72582. this._ondpadup = callback;
  72583. };
  72584. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  72585. if (newValue !== currentValue) {
  72586. if (newValue === 1) {
  72587. if (this._onbuttondown) {
  72588. this._onbuttondown(buttonType);
  72589. }
  72590. this.onButtonDownObservable.notifyObservers(buttonType);
  72591. }
  72592. if (newValue === 0) {
  72593. if (this._onbuttonup) {
  72594. this._onbuttonup(buttonType);
  72595. }
  72596. this.onButtonUpObservable.notifyObservers(buttonType);
  72597. }
  72598. }
  72599. return newValue;
  72600. };
  72601. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  72602. if (newValue !== currentValue) {
  72603. if (newValue === 1) {
  72604. if (this._ondpaddown) {
  72605. this._ondpaddown(buttonType);
  72606. }
  72607. this.onPadDownObservable.notifyObservers(buttonType);
  72608. }
  72609. if (newValue === 0) {
  72610. if (this._ondpadup) {
  72611. this._ondpadup(buttonType);
  72612. }
  72613. this.onPadUpObservable.notifyObservers(buttonType);
  72614. }
  72615. }
  72616. return newValue;
  72617. };
  72618. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  72619. /** Gets or sets value of A button */
  72620. get: function () {
  72621. return this._buttonA;
  72622. },
  72623. set: function (value) {
  72624. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  72625. },
  72626. enumerable: true,
  72627. configurable: true
  72628. });
  72629. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  72630. /** Gets or sets value of B button */
  72631. get: function () {
  72632. return this._buttonB;
  72633. },
  72634. set: function (value) {
  72635. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  72636. },
  72637. enumerable: true,
  72638. configurable: true
  72639. });
  72640. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  72641. /** Gets or sets value of X button */
  72642. get: function () {
  72643. return this._buttonX;
  72644. },
  72645. set: function (value) {
  72646. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  72647. },
  72648. enumerable: true,
  72649. configurable: true
  72650. });
  72651. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  72652. /** Gets or sets value of Y button */
  72653. get: function () {
  72654. return this._buttonY;
  72655. },
  72656. set: function (value) {
  72657. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  72658. },
  72659. enumerable: true,
  72660. configurable: true
  72661. });
  72662. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  72663. /** Gets or sets value of Start button */
  72664. get: function () {
  72665. return this._buttonStart;
  72666. },
  72667. set: function (value) {
  72668. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  72669. },
  72670. enumerable: true,
  72671. configurable: true
  72672. });
  72673. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  72674. /** Gets or sets value of Back button */
  72675. get: function () {
  72676. return this._buttonBack;
  72677. },
  72678. set: function (value) {
  72679. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  72680. },
  72681. enumerable: true,
  72682. configurable: true
  72683. });
  72684. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  72685. /** Gets or sets value of Left button */
  72686. get: function () {
  72687. return this._buttonLB;
  72688. },
  72689. set: function (value) {
  72690. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  72691. },
  72692. enumerable: true,
  72693. configurable: true
  72694. });
  72695. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  72696. /** Gets or sets value of Right button */
  72697. get: function () {
  72698. return this._buttonRB;
  72699. },
  72700. set: function (value) {
  72701. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  72702. },
  72703. enumerable: true,
  72704. configurable: true
  72705. });
  72706. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  72707. /** Gets or sets value of left stick */
  72708. get: function () {
  72709. return this._buttonLeftStick;
  72710. },
  72711. set: function (value) {
  72712. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  72713. },
  72714. enumerable: true,
  72715. configurable: true
  72716. });
  72717. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  72718. /** Gets or sets value of right stick */
  72719. get: function () {
  72720. return this._buttonRightStick;
  72721. },
  72722. set: function (value) {
  72723. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  72724. },
  72725. enumerable: true,
  72726. configurable: true
  72727. });
  72728. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  72729. /** Gets or sets value of DPad up */
  72730. get: function () {
  72731. return this._dPadUp;
  72732. },
  72733. set: function (value) {
  72734. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  72735. },
  72736. enumerable: true,
  72737. configurable: true
  72738. });
  72739. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  72740. /** Gets or sets value of DPad down */
  72741. get: function () {
  72742. return this._dPadDown;
  72743. },
  72744. set: function (value) {
  72745. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  72746. },
  72747. enumerable: true,
  72748. configurable: true
  72749. });
  72750. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  72751. /** Gets or sets value of DPad left */
  72752. get: function () {
  72753. return this._dPadLeft;
  72754. },
  72755. set: function (value) {
  72756. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  72757. },
  72758. enumerable: true,
  72759. configurable: true
  72760. });
  72761. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  72762. /** Gets or sets value of DPad right */
  72763. get: function () {
  72764. return this._dPadRight;
  72765. },
  72766. set: function (value) {
  72767. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  72768. },
  72769. enumerable: true,
  72770. configurable: true
  72771. });
  72772. /**
  72773. * Force the gamepad to synchronize with device values
  72774. */
  72775. Xbox360Pad.prototype.update = function () {
  72776. _super.prototype.update.call(this);
  72777. if (this._isXboxOnePad) {
  72778. this.buttonA = this.browserGamepad.buttons[0].value;
  72779. this.buttonB = this.browserGamepad.buttons[1].value;
  72780. this.buttonX = this.browserGamepad.buttons[2].value;
  72781. this.buttonY = this.browserGamepad.buttons[3].value;
  72782. this.buttonLB = this.browserGamepad.buttons[4].value;
  72783. this.buttonRB = this.browserGamepad.buttons[5].value;
  72784. this.leftTrigger = this.browserGamepad.axes[2];
  72785. this.rightTrigger = this.browserGamepad.axes[5];
  72786. this.buttonBack = this.browserGamepad.buttons[9].value;
  72787. this.buttonStart = this.browserGamepad.buttons[8].value;
  72788. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  72789. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  72790. this.dPadUp = this.browserGamepad.buttons[11].value;
  72791. this.dPadDown = this.browserGamepad.buttons[12].value;
  72792. this.dPadLeft = this.browserGamepad.buttons[13].value;
  72793. this.dPadRight = this.browserGamepad.buttons[14].value;
  72794. }
  72795. else {
  72796. this.buttonA = this.browserGamepad.buttons[0].value;
  72797. this.buttonB = this.browserGamepad.buttons[1].value;
  72798. this.buttonX = this.browserGamepad.buttons[2].value;
  72799. this.buttonY = this.browserGamepad.buttons[3].value;
  72800. this.buttonLB = this.browserGamepad.buttons[4].value;
  72801. this.buttonRB = this.browserGamepad.buttons[5].value;
  72802. this.leftTrigger = this.browserGamepad.buttons[6].value;
  72803. this.rightTrigger = this.browserGamepad.buttons[7].value;
  72804. this.buttonBack = this.browserGamepad.buttons[8].value;
  72805. this.buttonStart = this.browserGamepad.buttons[9].value;
  72806. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  72807. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  72808. this.dPadUp = this.browserGamepad.buttons[12].value;
  72809. this.dPadDown = this.browserGamepad.buttons[13].value;
  72810. this.dPadLeft = this.browserGamepad.buttons[14].value;
  72811. this.dPadRight = this.browserGamepad.buttons[15].value;
  72812. }
  72813. };
  72814. Xbox360Pad.prototype.dispose = function () {
  72815. _super.prototype.dispose.call(this);
  72816. this.onButtonDownObservable.clear();
  72817. this.onButtonUpObservable.clear();
  72818. this.onPadDownObservable.clear();
  72819. this.onPadUpObservable.clear();
  72820. };
  72821. return Xbox360Pad;
  72822. }(BABYLON.Gamepad));
  72823. BABYLON.Xbox360Pad = Xbox360Pad;
  72824. })(BABYLON || (BABYLON = {}));
  72825. //# sourceMappingURL=babylon.xboxGamepad.js.map
  72826. var BABYLON;
  72827. (function (BABYLON) {
  72828. /**
  72829. * Defines the types of pose enabled controllers that are supported
  72830. */
  72831. var PoseEnabledControllerType;
  72832. (function (PoseEnabledControllerType) {
  72833. /**
  72834. * HTC Vive
  72835. */
  72836. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  72837. /**
  72838. * Oculus Rift
  72839. */
  72840. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  72841. /**
  72842. * Windows mixed reality
  72843. */
  72844. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  72845. /**
  72846. * Samsung gear VR
  72847. */
  72848. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  72849. /**
  72850. * Google Daydream
  72851. */
  72852. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  72853. /**
  72854. * Generic
  72855. */
  72856. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  72857. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  72858. /**
  72859. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72860. */
  72861. var PoseEnabledControllerHelper = /** @class */ (function () {
  72862. function PoseEnabledControllerHelper() {
  72863. }
  72864. /**
  72865. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72866. * @param vrGamepad the gamepad to initialized
  72867. * @returns a vr controller of the type the gamepad identified as
  72868. */
  72869. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  72870. // Oculus Touch
  72871. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  72872. return new BABYLON.OculusTouchController(vrGamepad);
  72873. }
  72874. // Windows Mixed Reality controllers
  72875. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  72876. return new BABYLON.WindowsMotionController(vrGamepad);
  72877. }
  72878. // HTC Vive
  72879. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  72880. return new BABYLON.ViveController(vrGamepad);
  72881. }
  72882. // Samsung/Oculus Gear VR or Oculus Go
  72883. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  72884. return new BABYLON.GearVRController(vrGamepad);
  72885. }
  72886. // Google Daydream
  72887. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  72888. return new BABYLON.DaydreamController(vrGamepad);
  72889. }
  72890. // Generic
  72891. else {
  72892. return new BABYLON.GenericController(vrGamepad);
  72893. }
  72894. };
  72895. return PoseEnabledControllerHelper;
  72896. }());
  72897. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  72898. /**
  72899. * Defines the PoseEnabledController object that contains state of a vr capable controller
  72900. */
  72901. var PoseEnabledController = /** @class */ (function (_super) {
  72902. __extends(PoseEnabledController, _super);
  72903. /**
  72904. * Creates a new PoseEnabledController from a gamepad
  72905. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  72906. */
  72907. function PoseEnabledController(browserGamepad) {
  72908. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  72909. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72910. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72911. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  72912. /**
  72913. * The device position in babylon space
  72914. */
  72915. _this.devicePosition = BABYLON.Vector3.Zero();
  72916. /**
  72917. * The device rotation in babylon space
  72918. */
  72919. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  72920. /**
  72921. * The scale factor of the device in babylon space
  72922. */
  72923. _this.deviceScaleFactor = 1;
  72924. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  72925. /**
  72926. * Internal, matrix used to convert room space to babylon space
  72927. */
  72928. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72929. /**
  72930. * Node to be used when casting a ray from the controller
  72931. */
  72932. _this._pointingPoseNode = null;
  72933. _this._workingMatrix = BABYLON.Matrix.Identity();
  72934. /**
  72935. * @hidden
  72936. */
  72937. _this._meshAttachedObservable = new BABYLON.Observable();
  72938. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  72939. _this.controllerType = PoseEnabledControllerType.GENERIC;
  72940. _this.position = BABYLON.Vector3.Zero();
  72941. _this.rotationQuaternion = new BABYLON.Quaternion();
  72942. _this._calculatedPosition = BABYLON.Vector3.Zero();
  72943. _this._calculatedRotation = new BABYLON.Quaternion();
  72944. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  72945. return _this;
  72946. }
  72947. /**
  72948. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  72949. */
  72950. PoseEnabledController.prototype.update = function () {
  72951. _super.prototype.update.call(this);
  72952. this._updatePoseAndMesh();
  72953. };
  72954. /**
  72955. * Updates only the pose device and mesh without doing any button event checking
  72956. */
  72957. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  72958. var pose = this.browserGamepad.pose;
  72959. this.updateFromDevice(pose);
  72960. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  72961. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  72962. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72963. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  72964. if (this._mesh) {
  72965. this._mesh.position.copyFrom(this.devicePosition);
  72966. if (this._mesh.rotationQuaternion) {
  72967. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  72968. }
  72969. }
  72970. };
  72971. /**
  72972. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72973. * @param poseData raw pose fromthe device
  72974. */
  72975. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  72976. if (poseData) {
  72977. this.rawPose = poseData;
  72978. if (poseData.position) {
  72979. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  72980. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  72981. this._deviceRoomPosition.z *= -1;
  72982. }
  72983. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  72984. this._calculatedPosition.addInPlace(this.position);
  72985. }
  72986. var pose = this.rawPose;
  72987. if (poseData.orientation && pose.orientation) {
  72988. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  72989. if (this._mesh) {
  72990. if (this._mesh.getScene().useRightHandedSystem) {
  72991. this._deviceRoomRotationQuaternion.z *= -1;
  72992. this._deviceRoomRotationQuaternion.w *= -1;
  72993. }
  72994. else {
  72995. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  72996. }
  72997. }
  72998. // if the camera is set, rotate to the camera's rotation
  72999. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  73000. }
  73001. }
  73002. };
  73003. /**
  73004. * Attaches a mesh to the controller
  73005. * @param mesh the mesh to be attached
  73006. */
  73007. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  73008. if (this._mesh) {
  73009. this._mesh.parent = null;
  73010. }
  73011. this._mesh = mesh;
  73012. if (this._poseControlledCamera) {
  73013. this._mesh.parent = this._poseControlledCamera;
  73014. }
  73015. if (!this._mesh.rotationQuaternion) {
  73016. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  73017. }
  73018. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  73019. this._updatePoseAndMesh();
  73020. if (this._pointingPoseNode) {
  73021. var parents = [];
  73022. var obj = this._pointingPoseNode;
  73023. while (obj.parent) {
  73024. parents.push(obj.parent);
  73025. obj = obj.parent;
  73026. }
  73027. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  73028. }
  73029. this._meshAttachedObservable.notifyObservers(mesh);
  73030. };
  73031. /**
  73032. * Attaches the controllers mesh to a camera
  73033. * @param camera the camera the mesh should be attached to
  73034. */
  73035. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  73036. this._poseControlledCamera = camera;
  73037. if (this._mesh) {
  73038. this._mesh.parent = this._poseControlledCamera;
  73039. }
  73040. };
  73041. /**
  73042. * Disposes of the controller
  73043. */
  73044. PoseEnabledController.prototype.dispose = function () {
  73045. if (this._mesh) {
  73046. this._mesh.dispose();
  73047. }
  73048. this._mesh = null;
  73049. _super.prototype.dispose.call(this);
  73050. };
  73051. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  73052. /**
  73053. * The mesh that is attached to the controller
  73054. */
  73055. get: function () {
  73056. return this._mesh;
  73057. },
  73058. enumerable: true,
  73059. configurable: true
  73060. });
  73061. /**
  73062. * Gets the ray of the controller in the direction the controller is pointing
  73063. * @param length the length the resulting ray should be
  73064. * @returns a ray in the direction the controller is pointing
  73065. */
  73066. PoseEnabledController.prototype.getForwardRay = function (length) {
  73067. if (length === void 0) { length = 100; }
  73068. if (!this.mesh) {
  73069. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  73070. }
  73071. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  73072. var origin = m.getTranslation();
  73073. var forward = new BABYLON.Vector3(0, 0, -1);
  73074. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73075. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73076. return new BABYLON.Ray(origin, direction, length);
  73077. };
  73078. /**
  73079. * Name of the child mesh that can be used to cast a ray from the controller
  73080. */
  73081. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  73082. return PoseEnabledController;
  73083. }(BABYLON.Gamepad));
  73084. BABYLON.PoseEnabledController = PoseEnabledController;
  73085. })(BABYLON || (BABYLON = {}));
  73086. //# sourceMappingURL=babylon.poseEnabledController.js.map
  73087. var BABYLON;
  73088. (function (BABYLON) {
  73089. /**
  73090. * Defines the WebVRController object that represents controllers tracked in 3D space
  73091. */
  73092. var WebVRController = /** @class */ (function (_super) {
  73093. __extends(WebVRController, _super);
  73094. /**
  73095. * Creates a new WebVRController from a gamepad
  73096. * @param vrGamepad the gamepad that the WebVRController should be created from
  73097. */
  73098. function WebVRController(vrGamepad) {
  73099. var _this = _super.call(this, vrGamepad) || this;
  73100. // Observables
  73101. /**
  73102. * Fired when the trigger state has changed
  73103. */
  73104. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  73105. /**
  73106. * Fired when the main button state has changed
  73107. */
  73108. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  73109. /**
  73110. * Fired when the secondary button state has changed
  73111. */
  73112. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  73113. /**
  73114. * Fired when the pad state has changed
  73115. */
  73116. _this.onPadStateChangedObservable = new BABYLON.Observable();
  73117. /**
  73118. * Fired when controllers stick values have changed
  73119. */
  73120. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  73121. /**
  73122. * X and Y axis corrisponding to the controllers joystick
  73123. */
  73124. _this.pad = { x: 0, y: 0 };
  73125. // avoid GC, store state in a tmp object
  73126. _this._changes = {
  73127. pressChanged: false,
  73128. touchChanged: false,
  73129. valueChanged: false,
  73130. changed: false
  73131. };
  73132. _this._buttons = new Array(vrGamepad.buttons.length);
  73133. _this.hand = vrGamepad.hand;
  73134. return _this;
  73135. }
  73136. /**
  73137. * Fired when a controller button's state has changed
  73138. * @param callback the callback containing the button that was modified
  73139. */
  73140. WebVRController.prototype.onButtonStateChange = function (callback) {
  73141. this._onButtonStateChange = callback;
  73142. };
  73143. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  73144. /**
  73145. * The default controller model for the controller
  73146. */
  73147. get: function () {
  73148. return this._defaultModel;
  73149. },
  73150. enumerable: true,
  73151. configurable: true
  73152. });
  73153. /**
  73154. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  73155. */
  73156. WebVRController.prototype.update = function () {
  73157. _super.prototype.update.call(this);
  73158. for (var index = 0; index < this._buttons.length; index++) {
  73159. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  73160. }
  73161. ;
  73162. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  73163. this.pad.x = this.leftStick.x;
  73164. this.pad.y = this.leftStick.y;
  73165. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  73166. }
  73167. };
  73168. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  73169. if (!newState) {
  73170. newState = {
  73171. pressed: false,
  73172. touched: false,
  73173. value: 0
  73174. };
  73175. }
  73176. if (!currentState) {
  73177. this._buttons[buttonIndex] = {
  73178. pressed: newState.pressed,
  73179. touched: newState.touched,
  73180. value: newState.value
  73181. };
  73182. return;
  73183. }
  73184. this._checkChanges(newState, currentState);
  73185. if (this._changes.changed) {
  73186. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  73187. this._handleButtonChange(buttonIndex, newState, this._changes);
  73188. }
  73189. this._buttons[buttonIndex].pressed = newState.pressed;
  73190. this._buttons[buttonIndex].touched = newState.touched;
  73191. // oculus triggers are never 0, thou not touched.
  73192. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  73193. };
  73194. WebVRController.prototype._checkChanges = function (newState, currentState) {
  73195. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  73196. this._changes.touchChanged = newState.touched !== currentState.touched;
  73197. this._changes.valueChanged = newState.value !== currentState.value;
  73198. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  73199. return this._changes;
  73200. };
  73201. /**
  73202. * Disposes of th webVRCOntroller
  73203. */
  73204. WebVRController.prototype.dispose = function () {
  73205. _super.prototype.dispose.call(this);
  73206. this.onTriggerStateChangedObservable.clear();
  73207. this.onMainButtonStateChangedObservable.clear();
  73208. this.onSecondaryButtonStateChangedObservable.clear();
  73209. this.onPadStateChangedObservable.clear();
  73210. this.onPadValuesChangedObservable.clear();
  73211. };
  73212. return WebVRController;
  73213. }(BABYLON.PoseEnabledController));
  73214. BABYLON.WebVRController = WebVRController;
  73215. })(BABYLON || (BABYLON = {}));
  73216. //# sourceMappingURL=babylon.webVRController.js.map
  73217. var BABYLON;
  73218. (function (BABYLON) {
  73219. /**
  73220. * Oculus Touch Controller
  73221. */
  73222. var OculusTouchController = /** @class */ (function (_super) {
  73223. __extends(OculusTouchController, _super);
  73224. /**
  73225. * Creates a new OculusTouchController from a gamepad
  73226. * @param vrGamepad the gamepad that the controller should be created from
  73227. */
  73228. function OculusTouchController(vrGamepad) {
  73229. var _this = _super.call(this, vrGamepad) || this;
  73230. /**
  73231. * Fired when the secondary trigger on this controller is modified
  73232. */
  73233. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  73234. /**
  73235. * Fired when the thumb rest on this controller is modified
  73236. */
  73237. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  73238. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  73239. return _this;
  73240. }
  73241. /**
  73242. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73243. * @param scene scene in which to add meshes
  73244. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73245. */
  73246. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73247. var _this = this;
  73248. var meshName;
  73249. // Hand
  73250. if (this.hand === 'left') {
  73251. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  73252. }
  73253. else { // Right is the default if no hand is specified
  73254. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  73255. }
  73256. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  73257. /*
  73258. Parent Mesh name: oculus_touch_left
  73259. - body
  73260. - trigger
  73261. - thumbstick
  73262. - grip
  73263. - button_y
  73264. - button_x
  73265. - button_enter
  73266. */
  73267. _this._defaultModel = newMeshes[1];
  73268. _this.attachToMesh(_this._defaultModel);
  73269. if (meshLoaded) {
  73270. meshLoaded(_this._defaultModel);
  73271. }
  73272. });
  73273. };
  73274. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  73275. /**
  73276. * Fired when the A button on this controller is modified
  73277. */
  73278. get: function () {
  73279. if (this.hand === 'right') {
  73280. return this.onMainButtonStateChangedObservable;
  73281. }
  73282. else {
  73283. throw new Error('No A button on left hand');
  73284. }
  73285. },
  73286. enumerable: true,
  73287. configurable: true
  73288. });
  73289. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  73290. /**
  73291. * Fired when the B button on this controller is modified
  73292. */
  73293. get: function () {
  73294. if (this.hand === 'right') {
  73295. return this.onSecondaryButtonStateChangedObservable;
  73296. }
  73297. else {
  73298. throw new Error('No B button on left hand');
  73299. }
  73300. },
  73301. enumerable: true,
  73302. configurable: true
  73303. });
  73304. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  73305. /**
  73306. * Fired when the X button on this controller is modified
  73307. */
  73308. get: function () {
  73309. if (this.hand === 'left') {
  73310. return this.onMainButtonStateChangedObservable;
  73311. }
  73312. else {
  73313. throw new Error('No X button on right hand');
  73314. }
  73315. },
  73316. enumerable: true,
  73317. configurable: true
  73318. });
  73319. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  73320. /**
  73321. * Fired when the Y button on this controller is modified
  73322. */
  73323. get: function () {
  73324. if (this.hand === 'left') {
  73325. return this.onSecondaryButtonStateChangedObservable;
  73326. }
  73327. else {
  73328. throw new Error('No Y button on right hand');
  73329. }
  73330. },
  73331. enumerable: true,
  73332. configurable: true
  73333. });
  73334. /**
  73335. * Called once for each button that changed state since the last frame
  73336. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  73337. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  73338. * 2) secondary trigger (same)
  73339. * 3) A (right) X (left), touch, pressed = value
  73340. * 4) B / Y
  73341. * 5) thumb rest
  73342. * @param buttonIdx Which button index changed
  73343. * @param state New state of the button
  73344. * @param changes Which properties on the state changed since last frame
  73345. */
  73346. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73347. var notifyObject = state; //{ state: state, changes: changes };
  73348. var triggerDirection = this.hand === 'right' ? -1 : 1;
  73349. switch (buttonIdx) {
  73350. case 0:
  73351. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73352. return;
  73353. case 1: // index trigger
  73354. if (this._defaultModel) {
  73355. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  73356. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  73357. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  73358. }
  73359. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73360. return;
  73361. case 2: // secondary trigger
  73362. if (this._defaultModel) {
  73363. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  73364. }
  73365. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  73366. return;
  73367. case 3:
  73368. if (this._defaultModel) {
  73369. if (notifyObject.pressed) {
  73370. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  73371. }
  73372. else {
  73373. (this._defaultModel.getChildren()[1]).position.y = 0;
  73374. }
  73375. }
  73376. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73377. return;
  73378. case 4:
  73379. if (this._defaultModel) {
  73380. if (notifyObject.pressed) {
  73381. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73382. }
  73383. else {
  73384. (this._defaultModel.getChildren()[2]).position.y = 0;
  73385. }
  73386. }
  73387. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73388. return;
  73389. case 5:
  73390. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  73391. return;
  73392. }
  73393. };
  73394. /**
  73395. * Base Url for the controller model.
  73396. */
  73397. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  73398. /**
  73399. * File name for the left controller model.
  73400. */
  73401. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  73402. /**
  73403. * File name for the right controller model.
  73404. */
  73405. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  73406. return OculusTouchController;
  73407. }(BABYLON.WebVRController));
  73408. BABYLON.OculusTouchController = OculusTouchController;
  73409. })(BABYLON || (BABYLON = {}));
  73410. //# sourceMappingURL=babylon.oculusTouchController.js.map
  73411. var BABYLON;
  73412. (function (BABYLON) {
  73413. /**
  73414. * Vive Controller
  73415. */
  73416. var ViveController = /** @class */ (function (_super) {
  73417. __extends(ViveController, _super);
  73418. /**
  73419. * Creates a new ViveController from a gamepad
  73420. * @param vrGamepad the gamepad that the controller should be created from
  73421. */
  73422. function ViveController(vrGamepad) {
  73423. var _this = _super.call(this, vrGamepad) || this;
  73424. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  73425. _this._invertLeftStickY = true;
  73426. return _this;
  73427. }
  73428. /**
  73429. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73430. * @param scene scene in which to add meshes
  73431. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73432. */
  73433. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73434. var _this = this;
  73435. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  73436. /*
  73437. Parent Mesh name: ViveWand
  73438. - body
  73439. - r_gripper
  73440. - l_gripper
  73441. - menu_button
  73442. - system_button
  73443. - trackpad
  73444. - trigger
  73445. - LED
  73446. */
  73447. _this._defaultModel = newMeshes[1];
  73448. _this.attachToMesh(_this._defaultModel);
  73449. if (meshLoaded) {
  73450. meshLoaded(_this._defaultModel);
  73451. }
  73452. });
  73453. };
  73454. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  73455. /**
  73456. * Fired when the left button on this controller is modified
  73457. */
  73458. get: function () {
  73459. return this.onMainButtonStateChangedObservable;
  73460. },
  73461. enumerable: true,
  73462. configurable: true
  73463. });
  73464. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  73465. /**
  73466. * Fired when the right button on this controller is modified
  73467. */
  73468. get: function () {
  73469. return this.onMainButtonStateChangedObservable;
  73470. },
  73471. enumerable: true,
  73472. configurable: true
  73473. });
  73474. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  73475. /**
  73476. * Fired when the menu button on this controller is modified
  73477. */
  73478. get: function () {
  73479. return this.onSecondaryButtonStateChangedObservable;
  73480. },
  73481. enumerable: true,
  73482. configurable: true
  73483. });
  73484. /**
  73485. * Called once for each button that changed state since the last frame
  73486. * Vive mapping:
  73487. * 0: touchpad
  73488. * 1: trigger
  73489. * 2: left AND right buttons
  73490. * 3: menu button
  73491. * @param buttonIdx Which button index changed
  73492. * @param state New state of the button
  73493. * @param changes Which properties on the state changed since last frame
  73494. */
  73495. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73496. var notifyObject = state; //{ state: state, changes: changes };
  73497. switch (buttonIdx) {
  73498. case 0:
  73499. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73500. return;
  73501. case 1: // index trigger
  73502. if (this._defaultModel) {
  73503. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  73504. }
  73505. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73506. return;
  73507. case 2: // left AND right button
  73508. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73509. return;
  73510. case 3:
  73511. if (this._defaultModel) {
  73512. if (notifyObject.pressed) {
  73513. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73514. }
  73515. else {
  73516. (this._defaultModel.getChildren()[2]).position.y = 0;
  73517. }
  73518. }
  73519. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73520. return;
  73521. }
  73522. };
  73523. /**
  73524. * Base Url for the controller model.
  73525. */
  73526. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  73527. /**
  73528. * File name for the controller model.
  73529. */
  73530. ViveController.MODEL_FILENAME = 'wand.babylon';
  73531. return ViveController;
  73532. }(BABYLON.WebVRController));
  73533. BABYLON.ViveController = ViveController;
  73534. })(BABYLON || (BABYLON = {}));
  73535. //# sourceMappingURL=babylon.viveController.js.map
  73536. var BABYLON;
  73537. (function (BABYLON) {
  73538. /**
  73539. * Generic Controller
  73540. */
  73541. var GenericController = /** @class */ (function (_super) {
  73542. __extends(GenericController, _super);
  73543. /**
  73544. * Creates a new GenericController from a gamepad
  73545. * @param vrGamepad the gamepad that the controller should be created from
  73546. */
  73547. function GenericController(vrGamepad) {
  73548. return _super.call(this, vrGamepad) || this;
  73549. }
  73550. /**
  73551. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73552. * @param scene scene in which to add meshes
  73553. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73554. */
  73555. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73556. var _this = this;
  73557. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  73558. _this._defaultModel = newMeshes[1];
  73559. _this.attachToMesh(_this._defaultModel);
  73560. if (meshLoaded) {
  73561. meshLoaded(_this._defaultModel);
  73562. }
  73563. });
  73564. };
  73565. /**
  73566. * Called once for each button that changed state since the last frame
  73567. * @param buttonIdx Which button index changed
  73568. * @param state New state of the button
  73569. * @param changes Which properties on the state changed since last frame
  73570. */
  73571. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73572. console.log("Button id: " + buttonIdx + "state: ");
  73573. console.dir(state);
  73574. };
  73575. /**
  73576. * Base Url for the controller model.
  73577. */
  73578. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73579. /**
  73580. * File name for the controller model.
  73581. */
  73582. GenericController.MODEL_FILENAME = 'generic.babylon';
  73583. return GenericController;
  73584. }(BABYLON.WebVRController));
  73585. BABYLON.GenericController = GenericController;
  73586. })(BABYLON || (BABYLON = {}));
  73587. //# sourceMappingURL=babylon.genericController.js.map
  73588. var BABYLON;
  73589. (function (BABYLON) {
  73590. /**
  73591. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  73592. */
  73593. var LoadedMeshInfo = /** @class */ (function () {
  73594. function LoadedMeshInfo() {
  73595. /**
  73596. * Map of the button meshes contained in the controller
  73597. */
  73598. this.buttonMeshes = {};
  73599. /**
  73600. * Map of the axis meshes contained in the controller
  73601. */
  73602. this.axisMeshes = {};
  73603. }
  73604. return LoadedMeshInfo;
  73605. }());
  73606. /**
  73607. * Defines the WindowsMotionController object that the state of the windows motion controller
  73608. */
  73609. var WindowsMotionController = /** @class */ (function (_super) {
  73610. __extends(WindowsMotionController, _super);
  73611. /**
  73612. * Creates a new WindowsMotionController from a gamepad
  73613. * @param vrGamepad the gamepad that the controller should be created from
  73614. */
  73615. function WindowsMotionController(vrGamepad) {
  73616. var _this = _super.call(this, vrGamepad) || this;
  73617. _this._mapping = {
  73618. // Semantic button names
  73619. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  73620. // A mapping of the button name to glTF model node name
  73621. // that should be transformed by button value.
  73622. buttonMeshNames: {
  73623. 'trigger': 'SELECT',
  73624. 'menu': 'MENU',
  73625. 'grip': 'GRASP',
  73626. 'thumbstick': 'THUMBSTICK_PRESS',
  73627. 'trackpad': 'TOUCHPAD_PRESS'
  73628. },
  73629. // This mapping is used to translate from the Motion Controller to Babylon semantics
  73630. buttonObservableNames: {
  73631. 'trigger': 'onTriggerStateChangedObservable',
  73632. 'menu': 'onSecondaryButtonStateChangedObservable',
  73633. 'grip': 'onMainButtonStateChangedObservable',
  73634. 'thumbstick': 'onPadStateChangedObservable',
  73635. 'trackpad': 'onTrackpadChangedObservable'
  73636. },
  73637. // A mapping of the axis name to glTF model node name
  73638. // that should be transformed by axis value.
  73639. // This array mirrors the browserGamepad.axes array, such that
  73640. // the mesh corresponding to axis 0 is in this array index 0.
  73641. axisMeshNames: [
  73642. 'THUMBSTICK_X',
  73643. 'THUMBSTICK_Y',
  73644. 'TOUCHPAD_TOUCH_X',
  73645. 'TOUCHPAD_TOUCH_Y'
  73646. ],
  73647. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  73648. };
  73649. /**
  73650. * Fired when the trackpad on this controller is clicked
  73651. */
  73652. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  73653. /**
  73654. * Fired when the trackpad on this controller is modified
  73655. */
  73656. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  73657. /**
  73658. * The current x and y values of this controller's trackpad
  73659. */
  73660. _this.trackpad = { x: 0, y: 0 };
  73661. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  73662. _this._loadedMeshInfo = null;
  73663. return _this;
  73664. }
  73665. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  73666. /**
  73667. * Fired when the trigger on this controller is modified
  73668. */
  73669. get: function () {
  73670. return this.onTriggerStateChangedObservable;
  73671. },
  73672. enumerable: true,
  73673. configurable: true
  73674. });
  73675. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  73676. /**
  73677. * Fired when the menu button on this controller is modified
  73678. */
  73679. get: function () {
  73680. return this.onSecondaryButtonStateChangedObservable;
  73681. },
  73682. enumerable: true,
  73683. configurable: true
  73684. });
  73685. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  73686. /**
  73687. * Fired when the grip button on this controller is modified
  73688. */
  73689. get: function () {
  73690. return this.onMainButtonStateChangedObservable;
  73691. },
  73692. enumerable: true,
  73693. configurable: true
  73694. });
  73695. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  73696. /**
  73697. * Fired when the thumbstick button on this controller is modified
  73698. */
  73699. get: function () {
  73700. return this.onPadStateChangedObservable;
  73701. },
  73702. enumerable: true,
  73703. configurable: true
  73704. });
  73705. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  73706. /**
  73707. * Fired when the touchpad button on this controller is modified
  73708. */
  73709. get: function () {
  73710. return this.onTrackpadChangedObservable;
  73711. },
  73712. enumerable: true,
  73713. configurable: true
  73714. });
  73715. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  73716. /**
  73717. * Fired when the touchpad values on this controller are modified
  73718. */
  73719. get: function () {
  73720. return this.onTrackpadValuesChangedObservable;
  73721. },
  73722. enumerable: true,
  73723. configurable: true
  73724. });
  73725. WindowsMotionController.prototype._updateTrackpad = function () {
  73726. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  73727. this.trackpad.x = this.browserGamepad["axes"][2];
  73728. this.trackpad.y = this.browserGamepad["axes"][3];
  73729. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  73730. }
  73731. };
  73732. /**
  73733. * Called once per frame by the engine.
  73734. */
  73735. WindowsMotionController.prototype.update = function () {
  73736. _super.prototype.update.call(this);
  73737. if (this.browserGamepad.axes) {
  73738. this._updateTrackpad();
  73739. // Only need to animate axes if there is a loaded mesh
  73740. if (this._loadedMeshInfo) {
  73741. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  73742. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  73743. }
  73744. }
  73745. }
  73746. };
  73747. /**
  73748. * Called once for each button that changed state since the last frame
  73749. * @param buttonIdx Which button index changed
  73750. * @param state New state of the button
  73751. * @param changes Which properties on the state changed since last frame
  73752. */
  73753. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73754. var buttonName = this._mapping.buttons[buttonIdx];
  73755. if (!buttonName) {
  73756. return;
  73757. }
  73758. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  73759. this._updateTrackpad();
  73760. // Only emit events for buttons that we know how to map from index to name
  73761. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  73762. if (observable) {
  73763. observable.notifyObservers(state);
  73764. }
  73765. this._lerpButtonTransform(buttonName, state.value);
  73766. };
  73767. /**
  73768. * Moves the buttons on the controller mesh based on their current state
  73769. * @param buttonName the name of the button to move
  73770. * @param buttonValue the value of the button which determines the buttons new position
  73771. */
  73772. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  73773. // If there is no loaded mesh, there is nothing to transform.
  73774. if (!this._loadedMeshInfo) {
  73775. return;
  73776. }
  73777. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  73778. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73779. return;
  73780. }
  73781. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  73782. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  73783. };
  73784. /**
  73785. * Moves the axis on the controller mesh based on its current state
  73786. * @param axis the index of the axis
  73787. * @param axisValue the value of the axis which determines the meshes new position
  73788. * @hidden
  73789. */
  73790. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  73791. if (!this._loadedMeshInfo) {
  73792. return;
  73793. }
  73794. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  73795. if (!meshInfo) {
  73796. return;
  73797. }
  73798. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73799. return;
  73800. }
  73801. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  73802. var lerpValue = axisValue * 0.5 + 0.5;
  73803. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  73804. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  73805. };
  73806. /**
  73807. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73808. * @param scene scene in which to add meshes
  73809. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73810. */
  73811. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  73812. var _this = this;
  73813. if (forceDefault === void 0) { forceDefault = false; }
  73814. var path;
  73815. var filename;
  73816. // Checking if GLB loader is present
  73817. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  73818. // Determine the device specific folder based on the ID suffix
  73819. var device = 'default';
  73820. if (this.id && !forceDefault) {
  73821. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  73822. device = ((match && match[0]) || device);
  73823. }
  73824. // Hand
  73825. if (this.hand === 'left') {
  73826. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  73827. }
  73828. else { // Right is the default if no hand is specified
  73829. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  73830. }
  73831. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  73832. }
  73833. else {
  73834. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  73835. path = BABYLON.GenericController.MODEL_BASE_URL;
  73836. filename = BABYLON.GenericController.MODEL_FILENAME;
  73837. }
  73838. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  73839. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  73840. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  73841. if (!_this._loadedMeshInfo) {
  73842. return;
  73843. }
  73844. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  73845. _this.attachToMesh(_this._defaultModel);
  73846. if (meshLoaded) {
  73847. meshLoaded(_this._defaultModel);
  73848. }
  73849. }, null, function (scene, message) {
  73850. BABYLON.Tools.Log(message);
  73851. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  73852. if (!forceDefault) {
  73853. _this.initControllerMesh(scene, meshLoaded, true);
  73854. }
  73855. });
  73856. };
  73857. /**
  73858. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  73859. * can be transformed by button presses and axes values, based on this._mapping.
  73860. *
  73861. * @param scene scene in which the meshes exist
  73862. * @param meshes list of meshes that make up the controller model to process
  73863. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  73864. */
  73865. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  73866. var loadedMeshInfo = null;
  73867. // Create a new mesh to contain the glTF hierarchy
  73868. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  73869. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  73870. var childMesh = null;
  73871. for (var i = 0; i < meshes.length; i++) {
  73872. var mesh = meshes[i];
  73873. if (!mesh.parent) {
  73874. // Exclude controller meshes from picking results
  73875. mesh.isPickable = false;
  73876. // Handle root node, attach to the new parentMesh
  73877. childMesh = mesh;
  73878. break;
  73879. }
  73880. }
  73881. if (childMesh) {
  73882. childMesh.setParent(parentMesh);
  73883. // Create our mesh info. Note that this method will always return non-null.
  73884. loadedMeshInfo = this.createMeshInfo(parentMesh);
  73885. }
  73886. else {
  73887. BABYLON.Tools.Warn('Could not find root node in model file.');
  73888. }
  73889. return loadedMeshInfo;
  73890. };
  73891. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  73892. var loadedMeshInfo = new LoadedMeshInfo();
  73893. var i;
  73894. loadedMeshInfo.rootNode = rootNode;
  73895. // Reset the caches
  73896. loadedMeshInfo.buttonMeshes = {};
  73897. loadedMeshInfo.axisMeshes = {};
  73898. // Button Meshes
  73899. for (i = 0; i < this._mapping.buttons.length; i++) {
  73900. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  73901. if (!buttonMeshName) {
  73902. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  73903. continue;
  73904. }
  73905. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  73906. if (!buttonMesh) {
  73907. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  73908. continue;
  73909. }
  73910. var buttonMeshInfo = {
  73911. index: i,
  73912. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  73913. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  73914. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  73915. };
  73916. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  73917. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  73918. }
  73919. else {
  73920. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  73921. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  73922. '(VALUE: ' + !!buttonMeshInfo.value +
  73923. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  73924. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  73925. ')');
  73926. }
  73927. }
  73928. // Axis Meshes
  73929. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  73930. var axisMeshName = this._mapping.axisMeshNames[i];
  73931. if (!axisMeshName) {
  73932. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  73933. continue;
  73934. }
  73935. var axisMesh = getChildByName(rootNode, axisMeshName);
  73936. if (!axisMesh) {
  73937. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  73938. continue;
  73939. }
  73940. var axisMeshInfo = {
  73941. index: i,
  73942. value: getImmediateChildByName(axisMesh, 'VALUE'),
  73943. min: getImmediateChildByName(axisMesh, 'MIN'),
  73944. max: getImmediateChildByName(axisMesh, 'MAX')
  73945. };
  73946. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  73947. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  73948. }
  73949. else {
  73950. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  73951. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  73952. '(VALUE: ' + !!axisMeshInfo.value +
  73953. ', MIN: ' + !!axisMeshInfo.min +
  73954. ', MAX:' + !!axisMeshInfo.max +
  73955. ')');
  73956. }
  73957. }
  73958. // Pointing Ray
  73959. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  73960. if (!loadedMeshInfo.pointingPoseNode) {
  73961. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  73962. }
  73963. else {
  73964. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  73965. }
  73966. return loadedMeshInfo;
  73967. // Look through all children recursively. This will return null if no mesh exists with the given name.
  73968. function getChildByName(node, name) {
  73969. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  73970. }
  73971. // Look through only immediate children. This will return null if no mesh exists with the given name.
  73972. function getImmediateChildByName(node, name) {
  73973. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  73974. }
  73975. };
  73976. /**
  73977. * Gets the ray of the controller in the direction the controller is pointing
  73978. * @param length the length the resulting ray should be
  73979. * @returns a ray in the direction the controller is pointing
  73980. */
  73981. WindowsMotionController.prototype.getForwardRay = function (length) {
  73982. if (length === void 0) { length = 100; }
  73983. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  73984. return _super.prototype.getForwardRay.call(this, length);
  73985. }
  73986. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  73987. var origin = m.getTranslation();
  73988. var forward = new BABYLON.Vector3(0, 0, -1);
  73989. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73990. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73991. return new BABYLON.Ray(origin, direction, length);
  73992. };
  73993. /**
  73994. * Disposes of the controller
  73995. */
  73996. WindowsMotionController.prototype.dispose = function () {
  73997. _super.prototype.dispose.call(this);
  73998. this.onTrackpadChangedObservable.clear();
  73999. };
  74000. /**
  74001. * The base url used to load the left and right controller models
  74002. */
  74003. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  74004. /**
  74005. * The name of the left controller model file
  74006. */
  74007. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  74008. /**
  74009. * The name of the right controller model file
  74010. */
  74011. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  74012. /**
  74013. * The controller name prefix for this controller type
  74014. */
  74015. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  74016. /**
  74017. * The controller id pattern for this controller type
  74018. */
  74019. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  74020. return WindowsMotionController;
  74021. }(BABYLON.WebVRController));
  74022. BABYLON.WindowsMotionController = WindowsMotionController;
  74023. })(BABYLON || (BABYLON = {}));
  74024. //# sourceMappingURL=babylon.windowsMotionController.js.map
  74025. var BABYLON;
  74026. (function (BABYLON) {
  74027. /**
  74028. * Gear VR Controller
  74029. */
  74030. var GearVRController = /** @class */ (function (_super) {
  74031. __extends(GearVRController, _super);
  74032. /**
  74033. * Creates a new GearVRController from a gamepad
  74034. * @param vrGamepad the gamepad that the controller should be created from
  74035. */
  74036. function GearVRController(vrGamepad) {
  74037. var _this = _super.call(this, vrGamepad) || this;
  74038. _this._maxRotationDistFromHeadset = Math.PI / 5;
  74039. _this._draggedRoomRotation = 0;
  74040. _this._tmpVector = new BABYLON.Vector3();
  74041. _this._buttonIndexToObservableNameMap = [
  74042. 'onTrackpadChangedObservable',
  74043. 'onTriggerStateChangedObservable' // Trigger
  74044. ];
  74045. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  74046. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  74047. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  74048. return _this;
  74049. }
  74050. /**
  74051. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74052. * @param poseData raw pose fromthe device
  74053. */
  74054. GearVRController.prototype.updateFromDevice = function (poseData) {
  74055. _super.prototype.updateFromDevice.call(this, poseData);
  74056. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  74057. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  74058. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  74059. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  74060. // Find the radian distance away that the headset is from the controllers rotation
  74061. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  74062. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  74063. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  74064. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  74065. this._draggedRoomRotation += rotationAmount;
  74066. // Rotate controller around headset
  74067. var sin = Math.sin(-rotationAmount);
  74068. var cos = Math.cos(-rotationAmount);
  74069. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  74070. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  74071. }
  74072. }
  74073. }
  74074. };
  74075. /**
  74076. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74077. * @param scene scene in which to add meshes
  74078. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74079. */
  74080. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74081. var _this = this;
  74082. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  74083. // Offset the controller so it will rotate around the users wrist
  74084. var mesh = new BABYLON.Mesh("", scene);
  74085. newMeshes[1].parent = mesh;
  74086. newMeshes[1].position.z = -0.15;
  74087. _this._defaultModel = mesh;
  74088. _this.attachToMesh(_this._defaultModel);
  74089. if (meshLoaded) {
  74090. meshLoaded(_this._defaultModel);
  74091. }
  74092. });
  74093. };
  74094. /**
  74095. * Called once for each button that changed state since the last frame
  74096. * @param buttonIdx Which button index changed
  74097. * @param state New state of the button
  74098. * @param changes Which properties on the state changed since last frame
  74099. */
  74100. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74101. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  74102. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  74103. // Only emit events for buttons that we know how to map from index to observable
  74104. var observable = this[observableName];
  74105. if (observable) {
  74106. observable.notifyObservers(state);
  74107. }
  74108. }
  74109. };
  74110. /**
  74111. * Base Url for the controller model.
  74112. */
  74113. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74114. /**
  74115. * File name for the controller model.
  74116. */
  74117. GearVRController.MODEL_FILENAME = 'generic.babylon';
  74118. /**
  74119. * Gamepad Id prefix used to identify this controller.
  74120. */
  74121. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  74122. return GearVRController;
  74123. }(BABYLON.WebVRController));
  74124. BABYLON.GearVRController = GearVRController;
  74125. })(BABYLON || (BABYLON = {}));
  74126. //# sourceMappingURL=babylon.gearVRController.js.map
  74127. var BABYLON;
  74128. (function (BABYLON) {
  74129. /**
  74130. * Google Daydream controller
  74131. */
  74132. var DaydreamController = /** @class */ (function (_super) {
  74133. __extends(DaydreamController, _super);
  74134. /**
  74135. * Creates a new DaydreamController from a gamepad
  74136. * @param vrGamepad the gamepad that the controller should be created from
  74137. */
  74138. function DaydreamController(vrGamepad) {
  74139. var _this = _super.call(this, vrGamepad) || this;
  74140. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  74141. return _this;
  74142. }
  74143. /**
  74144. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74145. * @param scene scene in which to add meshes
  74146. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74147. */
  74148. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74149. var _this = this;
  74150. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  74151. _this._defaultModel = newMeshes[1];
  74152. _this.attachToMesh(_this._defaultModel);
  74153. if (meshLoaded) {
  74154. meshLoaded(_this._defaultModel);
  74155. }
  74156. });
  74157. };
  74158. /**
  74159. * Called once for each button that changed state since the last frame
  74160. * @param buttonIdx Which button index changed
  74161. * @param state New state of the button
  74162. * @param changes Which properties on the state changed since last frame
  74163. */
  74164. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74165. // Daydream controller only has 1 GamepadButton (on the trackpad).
  74166. if (buttonIdx === 0) {
  74167. var observable = this.onTriggerStateChangedObservable;
  74168. if (observable) {
  74169. observable.notifyObservers(state);
  74170. }
  74171. }
  74172. else {
  74173. // If the app or home buttons are ever made available
  74174. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  74175. }
  74176. };
  74177. /**
  74178. * Base Url for the controller model.
  74179. */
  74180. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74181. /**
  74182. * File name for the controller model.
  74183. */
  74184. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  74185. /**
  74186. * Gamepad Id prefix used to identify Daydream Controller.
  74187. */
  74188. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  74189. return DaydreamController;
  74190. }(BABYLON.WebVRController));
  74191. BABYLON.DaydreamController = DaydreamController;
  74192. })(BABYLON || (BABYLON = {}));
  74193. //# sourceMappingURL=babylon.daydreamController.js.map
  74194. var BABYLON;
  74195. (function (BABYLON) {
  74196. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  74197. get: function () {
  74198. if (!this._gamepadManager) {
  74199. this._gamepadManager = new BABYLON.GamepadManager(this);
  74200. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  74201. if (!component) {
  74202. component = new GamepadSystemSceneComponent(this);
  74203. this._addComponent(component);
  74204. }
  74205. }
  74206. return this._gamepadManager;
  74207. },
  74208. enumerable: true,
  74209. configurable: true
  74210. });
  74211. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  74212. this.add(new BABYLON.FreeCameraGamepadInput());
  74213. return this;
  74214. };
  74215. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  74216. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  74217. return this;
  74218. };
  74219. /**
  74220. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  74221. */
  74222. var GamepadSystemSceneComponent = /** @class */ (function () {
  74223. /**
  74224. * Creates a new instance of the component for the given scene
  74225. * @param scene Defines the scene to register the component in
  74226. */
  74227. function GamepadSystemSceneComponent(scene) {
  74228. /**
  74229. * The component name helpfull to identify the component in the list of scene components.
  74230. */
  74231. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  74232. this.scene = scene;
  74233. }
  74234. /**
  74235. * Registers the component in a given scene
  74236. */
  74237. GamepadSystemSceneComponent.prototype.register = function () {
  74238. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  74239. };
  74240. /**
  74241. * Rebuilds the elements related to this component in case of
  74242. * context lost for instance.
  74243. */
  74244. GamepadSystemSceneComponent.prototype.rebuild = function () {
  74245. // Nothing to do for gamepads
  74246. };
  74247. /**
  74248. * Disposes the component and the associated ressources
  74249. */
  74250. GamepadSystemSceneComponent.prototype.dispose = function () {
  74251. var gamepadManager = this.scene._gamepadManager;
  74252. if (gamepadManager) {
  74253. gamepadManager.dispose();
  74254. this.scene._gamepadManager = null;
  74255. }
  74256. };
  74257. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  74258. var gamepadManager = this.scene._gamepadManager;
  74259. if (gamepadManager && gamepadManager._isMonitoring) {
  74260. gamepadManager._checkGamepadsStatus();
  74261. }
  74262. };
  74263. return GamepadSystemSceneComponent;
  74264. }());
  74265. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  74266. })(BABYLON || (BABYLON = {}));
  74267. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  74268. var BABYLON;
  74269. (function (BABYLON) {
  74270. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  74271. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  74272. });
  74273. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  74274. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  74275. });
  74276. var FollowCamera = /** @class */ (function (_super) {
  74277. __extends(FollowCamera, _super);
  74278. function FollowCamera(name, position, scene, lockedTarget) {
  74279. if (lockedTarget === void 0) { lockedTarget = null; }
  74280. var _this = _super.call(this, name, position, scene) || this;
  74281. _this.radius = 12;
  74282. _this.rotationOffset = 0;
  74283. _this.heightOffset = 4;
  74284. _this.cameraAcceleration = 0.05;
  74285. _this.maxCameraSpeed = 20;
  74286. _this.lockedTarget = lockedTarget;
  74287. return _this;
  74288. }
  74289. FollowCamera.prototype.getRadians = function (degrees) {
  74290. return degrees * Math.PI / 180;
  74291. };
  74292. FollowCamera.prototype.follow = function (cameraTarget) {
  74293. if (!cameraTarget)
  74294. return;
  74295. var yRotation;
  74296. if (cameraTarget.rotationQuaternion) {
  74297. var rotMatrix = new BABYLON.Matrix();
  74298. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  74299. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  74300. }
  74301. else {
  74302. yRotation = cameraTarget.rotation.y;
  74303. }
  74304. var radians = this.getRadians(this.rotationOffset) + yRotation;
  74305. var targetPosition = cameraTarget.getAbsolutePosition();
  74306. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  74307. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  74308. var dx = targetX - this.position.x;
  74309. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  74310. var dz = (targetZ) - this.position.z;
  74311. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  74312. var vy = dy * this.cameraAcceleration;
  74313. var vz = dz * this.cameraAcceleration * 2;
  74314. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  74315. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74316. }
  74317. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  74318. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74319. }
  74320. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  74321. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74322. }
  74323. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  74324. this.setTarget(targetPosition);
  74325. };
  74326. FollowCamera.prototype._checkInputs = function () {
  74327. _super.prototype._checkInputs.call(this);
  74328. if (this.lockedTarget) {
  74329. this.follow(this.lockedTarget);
  74330. }
  74331. };
  74332. FollowCamera.prototype.getClassName = function () {
  74333. return "FollowCamera";
  74334. };
  74335. __decorate([
  74336. BABYLON.serialize()
  74337. ], FollowCamera.prototype, "radius", void 0);
  74338. __decorate([
  74339. BABYLON.serialize()
  74340. ], FollowCamera.prototype, "rotationOffset", void 0);
  74341. __decorate([
  74342. BABYLON.serialize()
  74343. ], FollowCamera.prototype, "heightOffset", void 0);
  74344. __decorate([
  74345. BABYLON.serialize()
  74346. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  74347. __decorate([
  74348. BABYLON.serialize()
  74349. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  74350. __decorate([
  74351. BABYLON.serializeAsMeshReference("lockedTargetId")
  74352. ], FollowCamera.prototype, "lockedTarget", void 0);
  74353. return FollowCamera;
  74354. }(BABYLON.TargetCamera));
  74355. BABYLON.FollowCamera = FollowCamera;
  74356. var ArcFollowCamera = /** @class */ (function (_super) {
  74357. __extends(ArcFollowCamera, _super);
  74358. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  74359. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  74360. _this.alpha = alpha;
  74361. _this.beta = beta;
  74362. _this.radius = radius;
  74363. _this.target = target;
  74364. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  74365. _this.follow();
  74366. return _this;
  74367. }
  74368. ArcFollowCamera.prototype.follow = function () {
  74369. if (!this.target) {
  74370. return;
  74371. }
  74372. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  74373. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  74374. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  74375. var targetPosition = this.target.getAbsolutePosition();
  74376. this.position = targetPosition.add(this._cartesianCoordinates);
  74377. this.setTarget(targetPosition);
  74378. };
  74379. ArcFollowCamera.prototype._checkInputs = function () {
  74380. _super.prototype._checkInputs.call(this);
  74381. this.follow();
  74382. };
  74383. ArcFollowCamera.prototype.getClassName = function () {
  74384. return "ArcFollowCamera";
  74385. };
  74386. return ArcFollowCamera;
  74387. }(BABYLON.TargetCamera));
  74388. BABYLON.ArcFollowCamera = ArcFollowCamera;
  74389. })(BABYLON || (BABYLON = {}));
  74390. //# sourceMappingURL=babylon.followCamera.js.map
  74391. var BABYLON;
  74392. (function (BABYLON) {
  74393. // We're mainly based on the logic defined into the FreeCamera code
  74394. var UniversalCamera = /** @class */ (function (_super) {
  74395. __extends(UniversalCamera, _super);
  74396. //-- end properties for backward compatibility for inputs
  74397. function UniversalCamera(name, position, scene) {
  74398. var _this = _super.call(this, name, position, scene) || this;
  74399. _this.inputs.addGamepad();
  74400. return _this;
  74401. }
  74402. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  74403. //-- Begin properties for backward compatibility for inputs
  74404. get: function () {
  74405. var gamepad = this.inputs.attached["gamepad"];
  74406. if (gamepad)
  74407. return gamepad.gamepadAngularSensibility;
  74408. return 0;
  74409. },
  74410. set: function (value) {
  74411. var gamepad = this.inputs.attached["gamepad"];
  74412. if (gamepad)
  74413. gamepad.gamepadAngularSensibility = value;
  74414. },
  74415. enumerable: true,
  74416. configurable: true
  74417. });
  74418. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  74419. get: function () {
  74420. var gamepad = this.inputs.attached["gamepad"];
  74421. if (gamepad)
  74422. return gamepad.gamepadMoveSensibility;
  74423. return 0;
  74424. },
  74425. set: function (value) {
  74426. var gamepad = this.inputs.attached["gamepad"];
  74427. if (gamepad)
  74428. gamepad.gamepadMoveSensibility = value;
  74429. },
  74430. enumerable: true,
  74431. configurable: true
  74432. });
  74433. UniversalCamera.prototype.getClassName = function () {
  74434. return "UniversalCamera";
  74435. };
  74436. return UniversalCamera;
  74437. }(BABYLON.TouchCamera));
  74438. BABYLON.UniversalCamera = UniversalCamera;
  74439. })(BABYLON || (BABYLON = {}));
  74440. //# sourceMappingURL=babylon.universalCamera.js.map
  74441. var BABYLON;
  74442. (function (BABYLON) {
  74443. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  74444. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  74445. });
  74446. // We're mainly based on the logic defined into the FreeCamera code
  74447. var GamepadCamera = /** @class */ (function (_super) {
  74448. __extends(GamepadCamera, _super);
  74449. //-- end properties for backward compatibility for inputs
  74450. function GamepadCamera(name, position, scene) {
  74451. return _super.call(this, name, position, scene) || this;
  74452. }
  74453. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  74454. //-- Begin properties for backward compatibility for inputs
  74455. get: function () {
  74456. var gamepad = this.inputs.attached["gamepad"];
  74457. if (gamepad)
  74458. return gamepad.gamepadAngularSensibility;
  74459. return 0;
  74460. },
  74461. set: function (value) {
  74462. var gamepad = this.inputs.attached["gamepad"];
  74463. if (gamepad)
  74464. gamepad.gamepadAngularSensibility = value;
  74465. },
  74466. enumerable: true,
  74467. configurable: true
  74468. });
  74469. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  74470. get: function () {
  74471. var gamepad = this.inputs.attached["gamepad"];
  74472. if (gamepad)
  74473. return gamepad.gamepadMoveSensibility;
  74474. return 0;
  74475. },
  74476. set: function (value) {
  74477. var gamepad = this.inputs.attached["gamepad"];
  74478. if (gamepad)
  74479. gamepad.gamepadMoveSensibility = value;
  74480. },
  74481. enumerable: true,
  74482. configurable: true
  74483. });
  74484. GamepadCamera.prototype.getClassName = function () {
  74485. return "GamepadCamera";
  74486. };
  74487. return GamepadCamera;
  74488. }(BABYLON.UniversalCamera));
  74489. BABYLON.GamepadCamera = GamepadCamera;
  74490. })(BABYLON || (BABYLON = {}));
  74491. //# sourceMappingURL=babylon.gamepadCamera.js.map
  74492. var BABYLON;
  74493. (function (BABYLON) {
  74494. var PostProcessRenderPipelineManager = /** @class */ (function () {
  74495. function PostProcessRenderPipelineManager() {
  74496. this._renderPipelines = {};
  74497. }
  74498. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  74499. this._renderPipelines[renderPipeline._name] = renderPipeline;
  74500. };
  74501. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  74502. if (unique === void 0) { unique = false; }
  74503. var renderPipeline = this._renderPipelines[renderPipelineName];
  74504. if (!renderPipeline) {
  74505. return;
  74506. }
  74507. renderPipeline._attachCameras(cameras, unique);
  74508. };
  74509. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  74510. var renderPipeline = this._renderPipelines[renderPipelineName];
  74511. if (!renderPipeline) {
  74512. return;
  74513. }
  74514. renderPipeline._detachCameras(cameras);
  74515. };
  74516. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74517. var renderPipeline = this._renderPipelines[renderPipelineName];
  74518. if (!renderPipeline) {
  74519. return;
  74520. }
  74521. renderPipeline._enableEffect(renderEffectName, cameras);
  74522. };
  74523. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74524. var renderPipeline = this._renderPipelines[renderPipelineName];
  74525. if (!renderPipeline) {
  74526. return;
  74527. }
  74528. renderPipeline._disableEffect(renderEffectName, cameras);
  74529. };
  74530. PostProcessRenderPipelineManager.prototype.update = function () {
  74531. for (var renderPipelineName in this._renderPipelines) {
  74532. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74533. var pipeline = this._renderPipelines[renderPipelineName];
  74534. if (!pipeline.isSupported) {
  74535. pipeline.dispose();
  74536. delete this._renderPipelines[renderPipelineName];
  74537. }
  74538. else {
  74539. pipeline._update();
  74540. }
  74541. }
  74542. }
  74543. };
  74544. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  74545. for (var renderPipelineName in this._renderPipelines) {
  74546. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74547. var pipeline = this._renderPipelines[renderPipelineName];
  74548. pipeline._rebuild();
  74549. }
  74550. }
  74551. };
  74552. PostProcessRenderPipelineManager.prototype.dispose = function () {
  74553. for (var renderPipelineName in this._renderPipelines) {
  74554. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74555. var pipeline = this._renderPipelines[renderPipelineName];
  74556. pipeline.dispose();
  74557. }
  74558. }
  74559. };
  74560. return PostProcessRenderPipelineManager;
  74561. }());
  74562. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  74563. })(BABYLON || (BABYLON = {}));
  74564. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  74565. var BABYLON;
  74566. (function (BABYLON) {
  74567. /**
  74568. * This represents a set of one or more post processes in Babylon.
  74569. * A post process can be used to apply a shader to a texture after it is rendered.
  74570. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  74571. */
  74572. var PostProcessRenderEffect = /** @class */ (function () {
  74573. /**
  74574. * Instantiates a post process render effect.
  74575. * A post process can be used to apply a shader to a texture after it is rendered.
  74576. * @param engine The engine the effect is tied to
  74577. * @param name The name of the effect
  74578. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  74579. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  74580. */
  74581. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  74582. this._name = name;
  74583. this._singleInstance = singleInstance || true;
  74584. this._getPostProcesses = getPostProcesses;
  74585. this._cameras = {};
  74586. this._indicesForCamera = {};
  74587. this._postProcesses = {};
  74588. }
  74589. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  74590. /**
  74591. * Checks if all the post processes in the effect are supported.
  74592. */
  74593. get: function () {
  74594. for (var index in this._postProcesses) {
  74595. if (this._postProcesses.hasOwnProperty(index)) {
  74596. var pps = this._postProcesses[index];
  74597. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  74598. if (!pps[ppIndex].isSupported) {
  74599. return false;
  74600. }
  74601. }
  74602. }
  74603. }
  74604. return true;
  74605. },
  74606. enumerable: true,
  74607. configurable: true
  74608. });
  74609. /**
  74610. * Updates the current state of the effect
  74611. */
  74612. PostProcessRenderEffect.prototype._update = function () {
  74613. };
  74614. /**
  74615. * Attaches the effect on cameras
  74616. * @param cameras The camera to attach to.
  74617. */
  74618. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  74619. var _this = this;
  74620. var cameraKey;
  74621. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74622. if (!cams) {
  74623. return;
  74624. }
  74625. for (var i = 0; i < cams.length; i++) {
  74626. var camera = cams[i];
  74627. var cameraName = camera.name;
  74628. if (this._singleInstance) {
  74629. cameraKey = 0;
  74630. }
  74631. else {
  74632. cameraKey = cameraName;
  74633. }
  74634. if (!this._postProcesses[cameraKey]) {
  74635. var postProcess = this._getPostProcesses();
  74636. if (postProcess) {
  74637. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  74638. }
  74639. }
  74640. if (!this._indicesForCamera[cameraName]) {
  74641. this._indicesForCamera[cameraName] = [];
  74642. }
  74643. this._postProcesses[cameraKey].forEach(function (postProcess) {
  74644. var index = camera.attachPostProcess(postProcess);
  74645. _this._indicesForCamera[cameraName].push(index);
  74646. });
  74647. if (!this._cameras[cameraName]) {
  74648. this._cameras[cameraName] = camera;
  74649. }
  74650. }
  74651. };
  74652. /**
  74653. * Detatches the effect on cameras
  74654. * @param cameras The camera to detatch from.
  74655. */
  74656. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  74657. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74658. if (!cams) {
  74659. return;
  74660. }
  74661. for (var i = 0; i < cams.length; i++) {
  74662. var camera = cams[i];
  74663. var cameraName = camera.name;
  74664. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74665. camera.detachPostProcess(postProcess);
  74666. });
  74667. if (this._cameras[cameraName]) {
  74668. //this._indicesForCamera.splice(index, 1);
  74669. this._cameras[cameraName] = null;
  74670. }
  74671. }
  74672. };
  74673. /**
  74674. * Enables the effect on given cameras
  74675. * @param cameras The camera to enable.
  74676. */
  74677. PostProcessRenderEffect.prototype._enable = function (cameras) {
  74678. var _this = this;
  74679. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74680. if (!cams) {
  74681. return;
  74682. }
  74683. for (var i = 0; i < cams.length; i++) {
  74684. var camera = cams[i];
  74685. var cameraName = camera.name;
  74686. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  74687. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  74688. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74689. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  74690. });
  74691. }
  74692. }
  74693. }
  74694. };
  74695. /**
  74696. * Disables the effect on the given cameras
  74697. * @param cameras The camera to disable.
  74698. */
  74699. PostProcessRenderEffect.prototype._disable = function (cameras) {
  74700. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74701. if (!cams) {
  74702. return;
  74703. }
  74704. for (var i = 0; i < cams.length; i++) {
  74705. var camera = cams[i];
  74706. var cameraName = camera.name;
  74707. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74708. camera.detachPostProcess(postProcess);
  74709. });
  74710. }
  74711. };
  74712. /**
  74713. * Gets a list of the post processes contained in the effect.
  74714. * @param camera The camera to get the post processes on.
  74715. * @returns The list of the post processes in the effect.
  74716. */
  74717. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  74718. if (this._singleInstance) {
  74719. return this._postProcesses[0];
  74720. }
  74721. else {
  74722. if (!camera) {
  74723. return null;
  74724. }
  74725. return this._postProcesses[camera.name];
  74726. }
  74727. };
  74728. return PostProcessRenderEffect;
  74729. }());
  74730. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  74731. })(BABYLON || (BABYLON = {}));
  74732. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  74733. var BABYLON;
  74734. (function (BABYLON) {
  74735. var PostProcessRenderPipeline = /** @class */ (function () {
  74736. function PostProcessRenderPipeline(engine, name) {
  74737. this.engine = engine;
  74738. this._name = name;
  74739. this._renderEffects = {};
  74740. this._renderEffectsForIsolatedPass = new Array();
  74741. this._cameras = [];
  74742. }
  74743. PostProcessRenderPipeline.prototype.getClassName = function () {
  74744. return "PostProcessRenderPipeline";
  74745. };
  74746. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  74747. get: function () {
  74748. for (var renderEffectName in this._renderEffects) {
  74749. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74750. if (!this._renderEffects[renderEffectName].isSupported) {
  74751. return false;
  74752. }
  74753. }
  74754. }
  74755. return true;
  74756. },
  74757. enumerable: true,
  74758. configurable: true
  74759. });
  74760. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  74761. this._renderEffects[renderEffect._name] = renderEffect;
  74762. };
  74763. // private
  74764. PostProcessRenderPipeline.prototype._rebuild = function () {
  74765. };
  74766. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  74767. var renderEffects = this._renderEffects[renderEffectName];
  74768. if (!renderEffects) {
  74769. return;
  74770. }
  74771. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74772. };
  74773. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  74774. var renderEffects = this._renderEffects[renderEffectName];
  74775. if (!renderEffects) {
  74776. return;
  74777. }
  74778. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74779. };
  74780. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  74781. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74782. if (!cams) {
  74783. return;
  74784. }
  74785. var indicesToDelete = [];
  74786. var i;
  74787. for (i = 0; i < cams.length; i++) {
  74788. var camera = cams[i];
  74789. var cameraName = camera.name;
  74790. if (this._cameras.indexOf(camera) === -1) {
  74791. this._cameras[cameraName] = camera;
  74792. }
  74793. else if (unique) {
  74794. indicesToDelete.push(i);
  74795. }
  74796. }
  74797. for (i = 0; i < indicesToDelete.length; i++) {
  74798. cameras.splice(indicesToDelete[i], 1);
  74799. }
  74800. for (var renderEffectName in this._renderEffects) {
  74801. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74802. this._renderEffects[renderEffectName]._attachCameras(cams);
  74803. }
  74804. }
  74805. };
  74806. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  74807. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74808. if (!cams) {
  74809. return;
  74810. }
  74811. for (var renderEffectName in this._renderEffects) {
  74812. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74813. this._renderEffects[renderEffectName]._detachCameras(cams);
  74814. }
  74815. }
  74816. for (var i = 0; i < cams.length; i++) {
  74817. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  74818. }
  74819. };
  74820. PostProcessRenderPipeline.prototype._update = function () {
  74821. for (var renderEffectName in this._renderEffects) {
  74822. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74823. this._renderEffects[renderEffectName]._update();
  74824. }
  74825. }
  74826. for (var i = 0; i < this._cameras.length; i++) {
  74827. var cameraName = this._cameras[i].name;
  74828. if (this._renderEffectsForIsolatedPass[cameraName]) {
  74829. this._renderEffectsForIsolatedPass[cameraName]._update();
  74830. }
  74831. }
  74832. };
  74833. PostProcessRenderPipeline.prototype._reset = function () {
  74834. this._renderEffects = {};
  74835. this._renderEffectsForIsolatedPass = new Array();
  74836. };
  74837. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  74838. // 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)
  74839. var effectKeys = Object.keys(this._renderEffects);
  74840. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  74841. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  74842. if (postProcesses) {
  74843. postProcesses[0].samples = sampleCount;
  74844. return true;
  74845. }
  74846. }
  74847. return false;
  74848. };
  74849. PostProcessRenderPipeline.prototype.dispose = function () {
  74850. // Must be implemented by children
  74851. };
  74852. __decorate([
  74853. BABYLON.serialize()
  74854. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  74855. return PostProcessRenderPipeline;
  74856. }());
  74857. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  74858. })(BABYLON || (BABYLON = {}));
  74859. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  74860. var BABYLON;
  74861. (function (BABYLON) {
  74862. /**
  74863. * This represents a depth renderer in Babylon.
  74864. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  74865. */
  74866. var DepthRenderer = /** @class */ (function () {
  74867. /**
  74868. * Instantiates a depth renderer
  74869. * @param scene The scene the renderer belongs to
  74870. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  74871. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  74872. */
  74873. function DepthRenderer(scene, type, camera) {
  74874. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74875. if (camera === void 0) { camera = null; }
  74876. var _this = this;
  74877. this._scene = scene;
  74878. this._camera = camera;
  74879. var engine = scene.getEngine();
  74880. // Render target
  74881. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  74882. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74883. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74884. this._depthMap.refreshRate = 1;
  74885. this._depthMap.renderParticles = false;
  74886. this._depthMap.renderList = null;
  74887. // Camera to get depth map from to support multiple concurrent cameras
  74888. this._depthMap.activeCamera = this._camera;
  74889. this._depthMap.ignoreCameraViewport = true;
  74890. this._depthMap.useCameraPostProcesses = false;
  74891. // set default depth value to 1.0 (far away)
  74892. this._depthMap.onClearObservable.add(function (engine) {
  74893. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  74894. });
  74895. // Custom render function
  74896. var renderSubMesh = function (subMesh) {
  74897. var mesh = subMesh.getRenderingMesh();
  74898. var scene = _this._scene;
  74899. var engine = scene.getEngine();
  74900. var material = subMesh.getMaterial();
  74901. if (!material) {
  74902. return;
  74903. }
  74904. // Culling and reverse (right handed system)
  74905. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74906. // Managing instances
  74907. var batch = mesh._getInstancesRenderList(subMesh._id);
  74908. if (batch.mustReturn) {
  74909. return;
  74910. }
  74911. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74912. var camera = _this._camera || scene.activeCamera;
  74913. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  74914. engine.enableEffect(_this._effect);
  74915. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74916. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74917. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  74918. // Alpha test
  74919. if (material && material.needAlphaTesting()) {
  74920. var alphaTexture = material.getAlphaTestTexture();
  74921. if (alphaTexture) {
  74922. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74923. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74924. }
  74925. }
  74926. // Bones
  74927. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74928. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74929. }
  74930. // Draw
  74931. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74932. }
  74933. };
  74934. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74935. var index;
  74936. if (depthOnlySubMeshes.length) {
  74937. engine.setColorWrite(false);
  74938. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74939. renderSubMesh(depthOnlySubMeshes.data[index]);
  74940. }
  74941. engine.setColorWrite(true);
  74942. }
  74943. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74944. renderSubMesh(opaqueSubMeshes.data[index]);
  74945. }
  74946. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74947. renderSubMesh(alphaTestSubMeshes.data[index]);
  74948. }
  74949. };
  74950. }
  74951. /**
  74952. * Creates the depth rendering effect and checks if the effect is ready.
  74953. * @param subMesh The submesh to be used to render the depth map of
  74954. * @param useInstances If multiple world instances should be used
  74955. * @returns if the depth renderer is ready to render the depth map
  74956. */
  74957. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  74958. var material = subMesh.getMaterial();
  74959. if (material.disableDepthWrite) {
  74960. return false;
  74961. }
  74962. var defines = [];
  74963. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74964. var mesh = subMesh.getMesh();
  74965. // Alpha test
  74966. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  74967. defines.push("#define ALPHATEST");
  74968. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74969. attribs.push(BABYLON.VertexBuffer.UVKind);
  74970. defines.push("#define UV1");
  74971. }
  74972. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74973. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74974. defines.push("#define UV2");
  74975. }
  74976. }
  74977. // Bones
  74978. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74979. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74980. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74981. if (mesh.numBoneInfluencers > 4) {
  74982. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74983. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74984. }
  74985. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74986. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74987. }
  74988. else {
  74989. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74990. }
  74991. // Instances
  74992. if (useInstances) {
  74993. defines.push("#define INSTANCES");
  74994. attribs.push("world0");
  74995. attribs.push("world1");
  74996. attribs.push("world2");
  74997. attribs.push("world3");
  74998. }
  74999. // Get correct effect
  75000. var join = defines.join("\n");
  75001. if (this._cachedDefines !== join) {
  75002. this._cachedDefines = join;
  75003. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  75004. }
  75005. return this._effect.isReady();
  75006. };
  75007. /**
  75008. * Gets the texture which the depth map will be written to.
  75009. * @returns The depth map texture
  75010. */
  75011. DepthRenderer.prototype.getDepthMap = function () {
  75012. return this._depthMap;
  75013. };
  75014. /**
  75015. * Disposes of the depth renderer.
  75016. */
  75017. DepthRenderer.prototype.dispose = function () {
  75018. this._depthMap.dispose();
  75019. };
  75020. return DepthRenderer;
  75021. }());
  75022. BABYLON.DepthRenderer = DepthRenderer;
  75023. })(BABYLON || (BABYLON = {}));
  75024. //# sourceMappingURL=babylon.depthRenderer.js.map
  75025. var BABYLON;
  75026. (function (BABYLON) {
  75027. var SSAORenderingPipeline = /** @class */ (function (_super) {
  75028. __extends(SSAORenderingPipeline, _super);
  75029. /**
  75030. * @constructor
  75031. * @param {string} name - The rendering pipeline name
  75032. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75033. * @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 }
  75034. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75035. */
  75036. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  75037. var _this = _super.call(this, scene.getEngine(), name) || this;
  75038. // Members
  75039. /**
  75040. * The PassPostProcess id in the pipeline that contains the original scene color
  75041. */
  75042. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75043. /**
  75044. * The SSAO PostProcess id in the pipeline
  75045. */
  75046. _this.SSAORenderEffect = "SSAORenderEffect";
  75047. /**
  75048. * The horizontal blur PostProcess id in the pipeline
  75049. */
  75050. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75051. /**
  75052. * The vertical blur PostProcess id in the pipeline
  75053. */
  75054. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75055. /**
  75056. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75057. */
  75058. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75059. /**
  75060. * The output strength of the SSAO post-process. Default value is 1.0.
  75061. */
  75062. _this.totalStrength = 1.0;
  75063. /**
  75064. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  75065. */
  75066. _this.radius = 0.0001;
  75067. /**
  75068. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  75069. * Must not be equal to fallOff and superior to fallOff.
  75070. * Default value is 0.975
  75071. */
  75072. _this.area = 0.0075;
  75073. /**
  75074. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  75075. * Must not be equal to area and inferior to area.
  75076. * Default value is 0.0
  75077. */
  75078. _this.fallOff = 0.000001;
  75079. /**
  75080. * The base color of the SSAO post-process
  75081. * The final result is "base + ssao" between [0, 1]
  75082. */
  75083. _this.base = 0.5;
  75084. _this._firstUpdate = true;
  75085. _this._scene = scene;
  75086. // Set up assets
  75087. _this._createRandomTexture();
  75088. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75089. var ssaoRatio = ratio.ssaoRatio || ratio;
  75090. var combineRatio = ratio.combineRatio || ratio;
  75091. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75092. _this._createSSAOPostProcess(ssaoRatio);
  75093. _this._createBlurPostProcess(ssaoRatio);
  75094. _this._createSSAOCombinePostProcess(combineRatio);
  75095. // Set up pipeline
  75096. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75097. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75098. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75099. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75100. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75101. // Finish
  75102. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75103. if (cameras)
  75104. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75105. return _this;
  75106. }
  75107. // Public Methods
  75108. /**
  75109. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75110. */
  75111. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75112. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75113. for (var i = 0; i < this._scene.cameras.length; i++) {
  75114. var camera = this._scene.cameras[i];
  75115. this._originalColorPostProcess.dispose(camera);
  75116. this._ssaoPostProcess.dispose(camera);
  75117. this._blurHPostProcess.dispose(camera);
  75118. this._blurVPostProcess.dispose(camera);
  75119. this._ssaoCombinePostProcess.dispose(camera);
  75120. }
  75121. this._randomTexture.dispose();
  75122. if (disableDepthRender)
  75123. this._scene.disableDepthRenderer();
  75124. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75125. _super.prototype.dispose.call(this);
  75126. };
  75127. // Private Methods
  75128. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  75129. var _this = this;
  75130. var size = 16;
  75131. 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);
  75132. 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);
  75133. this._blurHPostProcess.onActivateObservable.add(function () {
  75134. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  75135. _this._blurHPostProcess.kernel = size * dw;
  75136. });
  75137. this._blurVPostProcess.onActivateObservable.add(function () {
  75138. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  75139. _this._blurVPostProcess.kernel = size * dw;
  75140. });
  75141. };
  75142. SSAORenderingPipeline.prototype._rebuild = function () {
  75143. this._firstUpdate = true;
  75144. _super.prototype._rebuild.call(this);
  75145. };
  75146. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75147. var _this = this;
  75148. var numSamples = 16;
  75149. var sampleSphere = [
  75150. 0.5381, 0.1856, -0.4319,
  75151. 0.1379, 0.2486, 0.4430,
  75152. 0.3371, 0.5679, -0.0057,
  75153. -0.6999, -0.0451, -0.0019,
  75154. 0.0689, -0.1598, -0.8547,
  75155. 0.0560, 0.0069, -0.1843,
  75156. -0.0146, 0.1402, 0.0762,
  75157. 0.0100, -0.1924, -0.0344,
  75158. -0.3577, -0.5301, -0.4358,
  75159. -0.3169, 0.1063, 0.0158,
  75160. 0.0103, -0.5869, 0.0046,
  75161. -0.0897, -0.4940, 0.3287,
  75162. 0.7119, -0.0154, -0.0918,
  75163. -0.0533, 0.0596, -0.5411,
  75164. 0.0352, -0.0631, 0.5460,
  75165. -0.4776, 0.2847, -0.0271
  75166. ];
  75167. var samplesFactor = 1.0 / numSamples;
  75168. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  75169. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75170. "area", "fallOff", "base", "range", "viewport"
  75171. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75172. this._ssaoPostProcess.onApply = function (effect) {
  75173. if (_this._firstUpdate) {
  75174. effect.setArray3("sampleSphere", sampleSphere);
  75175. effect.setFloat("samplesFactor", samplesFactor);
  75176. effect.setFloat("randTextureTiles", 4.0);
  75177. }
  75178. effect.setFloat("totalStrength", _this.totalStrength);
  75179. effect.setFloat("radius", _this.radius);
  75180. effect.setFloat("area", _this.area);
  75181. effect.setFloat("fallOff", _this.fallOff);
  75182. effect.setFloat("base", _this.base);
  75183. effect.setTexture("textureSampler", _this._depthTexture);
  75184. effect.setTexture("randomSampler", _this._randomTexture);
  75185. };
  75186. };
  75187. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75188. var _this = this;
  75189. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75190. this._ssaoCombinePostProcess.onApply = function (effect) {
  75191. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  75192. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75193. };
  75194. };
  75195. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  75196. var size = 512;
  75197. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75198. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75199. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75200. var context = this._randomTexture.getContext();
  75201. var rand = function (min, max) {
  75202. return Math.random() * (max - min) + min;
  75203. };
  75204. var randVector = BABYLON.Vector3.Zero();
  75205. for (var x = 0; x < size; x++) {
  75206. for (var y = 0; y < size; y++) {
  75207. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  75208. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  75209. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  75210. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75211. context.fillRect(x, y, 1, 1);
  75212. }
  75213. }
  75214. this._randomTexture.update(false);
  75215. };
  75216. __decorate([
  75217. BABYLON.serialize()
  75218. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  75219. __decorate([
  75220. BABYLON.serialize()
  75221. ], SSAORenderingPipeline.prototype, "radius", void 0);
  75222. __decorate([
  75223. BABYLON.serialize()
  75224. ], SSAORenderingPipeline.prototype, "area", void 0);
  75225. __decorate([
  75226. BABYLON.serialize()
  75227. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  75228. __decorate([
  75229. BABYLON.serialize()
  75230. ], SSAORenderingPipeline.prototype, "base", void 0);
  75231. return SSAORenderingPipeline;
  75232. }(BABYLON.PostProcessRenderPipeline));
  75233. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  75234. })(BABYLON || (BABYLON = {}));
  75235. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  75236. var BABYLON;
  75237. (function (BABYLON) {
  75238. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  75239. __extends(SSAO2RenderingPipeline, _super);
  75240. /**
  75241. * @constructor
  75242. * @param {string} name - The rendering pipeline name
  75243. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75244. * @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 }
  75245. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75246. */
  75247. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  75248. var _this = _super.call(this, scene.getEngine(), name) || this;
  75249. // Members
  75250. /**
  75251. * The PassPostProcess id in the pipeline that contains the original scene color
  75252. */
  75253. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75254. /**
  75255. * The SSAO PostProcess id in the pipeline
  75256. */
  75257. _this.SSAORenderEffect = "SSAORenderEffect";
  75258. /**
  75259. * The horizontal blur PostProcess id in the pipeline
  75260. */
  75261. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75262. /**
  75263. * The vertical blur PostProcess id in the pipeline
  75264. */
  75265. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75266. /**
  75267. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75268. */
  75269. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75270. /**
  75271. * The output strength of the SSAO post-process. Default value is 1.0.
  75272. */
  75273. _this.totalStrength = 1.0;
  75274. /**
  75275. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  75276. */
  75277. _this.maxZ = 100.0;
  75278. /**
  75279. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  75280. */
  75281. _this.minZAspect = 0.2;
  75282. /**
  75283. * Number of samples used for the SSAO calculations. Default value is 8
  75284. */
  75285. _this._samples = 8;
  75286. /**
  75287. * Are we using bilateral blur ?
  75288. */
  75289. _this._expensiveBlur = true;
  75290. /**
  75291. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  75292. */
  75293. _this.radius = 2.0;
  75294. /**
  75295. * The base color of the SSAO post-process
  75296. * The final result is "base + ssao" between [0, 1]
  75297. */
  75298. _this.base = 0.1;
  75299. _this._firstUpdate = true;
  75300. _this._scene = scene;
  75301. _this._ratio = ratio;
  75302. if (!_this.isSupported) {
  75303. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  75304. return _this;
  75305. }
  75306. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  75307. var blurRatio = _this._ratio.blurRatio || ratio;
  75308. // Set up assets
  75309. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  75310. _this._createRandomTexture();
  75311. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  75312. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  75313. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75314. _this._createSSAOPostProcess(1.0);
  75315. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  75316. _this._createSSAOCombinePostProcess(blurRatio);
  75317. // Set up pipeline
  75318. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75319. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75320. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75321. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75322. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75323. // Finish
  75324. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75325. if (cameras)
  75326. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75327. return _this;
  75328. }
  75329. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  75330. get: function () {
  75331. return this._samples;
  75332. },
  75333. set: function (n) {
  75334. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  75335. this._samples = n;
  75336. this._sampleSphere = this._generateHemisphere();
  75337. this._firstUpdate = true;
  75338. },
  75339. enumerable: true,
  75340. configurable: true
  75341. });
  75342. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  75343. get: function () {
  75344. return this._expensiveBlur;
  75345. },
  75346. set: function (b) {
  75347. 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"]);
  75348. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  75349. this._expensiveBlur = b;
  75350. this._firstUpdate = true;
  75351. },
  75352. enumerable: true,
  75353. configurable: true
  75354. });
  75355. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  75356. /**
  75357. * Support test.
  75358. */
  75359. get: function () {
  75360. var engine = BABYLON.Engine.LastCreatedEngine;
  75361. if (!engine) {
  75362. return false;
  75363. }
  75364. return engine.getCaps().drawBuffersExtension;
  75365. },
  75366. enumerable: true,
  75367. configurable: true
  75368. });
  75369. // Public Methods
  75370. /**
  75371. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75372. */
  75373. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  75374. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  75375. for (var i = 0; i < this._scene.cameras.length; i++) {
  75376. var camera = this._scene.cameras[i];
  75377. this._originalColorPostProcess.dispose(camera);
  75378. this._ssaoPostProcess.dispose(camera);
  75379. this._blurHPostProcess.dispose(camera);
  75380. this._blurVPostProcess.dispose(camera);
  75381. this._ssaoCombinePostProcess.dispose(camera);
  75382. }
  75383. this._randomTexture.dispose();
  75384. if (disableGeometryBufferRenderer)
  75385. this._scene.disableGeometryBufferRenderer();
  75386. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75387. _super.prototype.dispose.call(this);
  75388. };
  75389. // Private Methods
  75390. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  75391. var _this = this;
  75392. this._samplerOffsets = [];
  75393. var expensive = this.expensiveBlur;
  75394. for (var i = -8; i < 8; i++) {
  75395. this._samplerOffsets.push(i * 2 + 0.5);
  75396. }
  75397. 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");
  75398. this._blurHPostProcess.onApply = function (effect) {
  75399. if (!_this._scene.activeCamera) {
  75400. return;
  75401. }
  75402. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  75403. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75404. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75405. effect.setFloat("radius", _this.radius);
  75406. effect.setTexture("depthSampler", _this._depthTexture);
  75407. if (_this._firstUpdate) {
  75408. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75409. }
  75410. };
  75411. 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");
  75412. this._blurVPostProcess.onApply = function (effect) {
  75413. if (!_this._scene.activeCamera) {
  75414. return;
  75415. }
  75416. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  75417. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75418. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75419. effect.setFloat("radius", _this.radius);
  75420. effect.setTexture("depthSampler", _this._depthTexture);
  75421. if (_this._firstUpdate) {
  75422. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75423. _this._firstUpdate = false;
  75424. }
  75425. };
  75426. };
  75427. SSAO2RenderingPipeline.prototype._rebuild = function () {
  75428. this._firstUpdate = true;
  75429. _super.prototype._rebuild.call(this);
  75430. };
  75431. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  75432. var numSamples = this.samples;
  75433. var result = [];
  75434. var vector, scale;
  75435. var rand = function (min, max) {
  75436. return Math.random() * (max - min) + min;
  75437. };
  75438. var i = 0;
  75439. while (i < numSamples) {
  75440. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  75441. vector.normalize();
  75442. scale = i / numSamples;
  75443. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  75444. vector.scaleInPlace(scale);
  75445. result.push(vector.x, vector.y, vector.z);
  75446. i++;
  75447. }
  75448. return result;
  75449. };
  75450. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75451. var _this = this;
  75452. var numSamples = this.samples;
  75453. this._sampleSphere = this._generateHemisphere();
  75454. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  75455. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75456. "base", "range", "projection", "near", "far", "texelSize",
  75457. "xViewport", "yViewport", "maxZ", "minZAspect"
  75458. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75459. this._ssaoPostProcess.onApply = function (effect) {
  75460. if (_this._firstUpdate) {
  75461. effect.setArray3("sampleSphere", _this._sampleSphere);
  75462. effect.setFloat("randTextureTiles", 4.0);
  75463. }
  75464. if (!_this._scene.activeCamera) {
  75465. return;
  75466. }
  75467. effect.setFloat("samplesFactor", 1 / _this.samples);
  75468. effect.setFloat("totalStrength", _this.totalStrength);
  75469. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  75470. effect.setFloat("radius", _this.radius);
  75471. effect.setFloat("maxZ", _this.maxZ);
  75472. effect.setFloat("minZAspect", _this.minZAspect);
  75473. effect.setFloat("base", _this.base);
  75474. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75475. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75476. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  75477. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  75478. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  75479. effect.setTexture("textureSampler", _this._depthTexture);
  75480. effect.setTexture("normalSampler", _this._normalTexture);
  75481. effect.setTexture("randomSampler", _this._randomTexture);
  75482. };
  75483. };
  75484. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75485. var _this = this;
  75486. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75487. this._ssaoCombinePostProcess.onApply = function (effect) {
  75488. var viewport = _this._scene.activeCamera.viewport;
  75489. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  75490. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75491. };
  75492. };
  75493. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  75494. var size = 512;
  75495. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75496. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75497. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75498. var context = this._randomTexture.getContext();
  75499. var rand = function (min, max) {
  75500. return Math.random() * (max - min) + min;
  75501. };
  75502. var randVector = BABYLON.Vector3.Zero();
  75503. for (var x = 0; x < size; x++) {
  75504. for (var y = 0; y < size; y++) {
  75505. randVector.x = rand(0.0, 1.0);
  75506. randVector.y = rand(0.0, 1.0);
  75507. randVector.z = 0.0;
  75508. randVector.normalize();
  75509. randVector.scaleInPlace(255);
  75510. randVector.x = Math.floor(randVector.x);
  75511. randVector.y = Math.floor(randVector.y);
  75512. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75513. context.fillRect(x, y, 1, 1);
  75514. }
  75515. }
  75516. this._randomTexture.update(false);
  75517. };
  75518. /**
  75519. * Serialize the rendering pipeline (Used when exporting)
  75520. * @returns the serialized object
  75521. */
  75522. SSAO2RenderingPipeline.prototype.serialize = function () {
  75523. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75524. serializationObject.customType = "SSAO2RenderingPipeline";
  75525. return serializationObject;
  75526. };
  75527. /**
  75528. * Parse the serialized pipeline
  75529. * @param source Source pipeline.
  75530. * @param scene The scene to load the pipeline to.
  75531. * @param rootUrl The URL of the serialized pipeline.
  75532. * @returns An instantiated pipeline from the serialized object.
  75533. */
  75534. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  75535. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75536. };
  75537. __decorate([
  75538. BABYLON.serialize()
  75539. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  75540. __decorate([
  75541. BABYLON.serialize()
  75542. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  75543. __decorate([
  75544. BABYLON.serialize()
  75545. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  75546. __decorate([
  75547. BABYLON.serialize("samples")
  75548. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  75549. __decorate([
  75550. BABYLON.serialize()
  75551. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  75552. __decorate([
  75553. BABYLON.serialize("expensiveBlur")
  75554. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  75555. __decorate([
  75556. BABYLON.serialize()
  75557. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  75558. __decorate([
  75559. BABYLON.serialize()
  75560. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  75561. return SSAO2RenderingPipeline;
  75562. }(BABYLON.PostProcessRenderPipeline));
  75563. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  75564. })(BABYLON || (BABYLON = {}));
  75565. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  75566. // BABYLON.JS Chromatic Aberration GLSL Shader
  75567. // Author: Olivier Guyot
  75568. // Separates very slightly R, G and B colors on the edges of the screen
  75569. // Inspired by Francois Tarlier & Martins Upitis
  75570. var BABYLON;
  75571. (function (BABYLON) {
  75572. var LensRenderingPipeline = /** @class */ (function (_super) {
  75573. __extends(LensRenderingPipeline, _super);
  75574. /**
  75575. * @constructor
  75576. *
  75577. * Effect parameters are as follow:
  75578. * {
  75579. * chromatic_aberration: number; // from 0 to x (1 for realism)
  75580. * edge_blur: number; // from 0 to x (1 for realism)
  75581. * distortion: number; // from 0 to x (1 for realism)
  75582. * grain_amount: number; // from 0 to 1
  75583. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  75584. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  75585. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  75586. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  75587. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  75588. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  75589. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  75590. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  75591. * }
  75592. * Note: if an effect parameter is unset, effect is disabled
  75593. *
  75594. * @param {string} name - The rendering pipeline name
  75595. * @param {object} parameters - An object containing all parameters (see above)
  75596. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75597. * @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)
  75598. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75599. */
  75600. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  75601. if (ratio === void 0) { ratio = 1.0; }
  75602. var _this = _super.call(this, scene.getEngine(), name) || this;
  75603. // Lens effects can be of the following:
  75604. // - chromatic aberration (slight shift of RGB colors)
  75605. // - blur on the edge of the lens
  75606. // - lens distortion
  75607. // - depth-of-field blur & highlights enhancing
  75608. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  75609. // - grain effect (noise or custom texture)
  75610. // Two additional texture samplers are needed:
  75611. // - depth map (for depth-of-field)
  75612. // - grain texture
  75613. /**
  75614. * The chromatic aberration PostProcess id in the pipeline
  75615. */
  75616. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  75617. /**
  75618. * The highlights enhancing PostProcess id in the pipeline
  75619. */
  75620. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  75621. /**
  75622. * The depth-of-field PostProcess id in the pipeline
  75623. */
  75624. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  75625. _this._scene = scene;
  75626. // Fetch texture samplers
  75627. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75628. if (parameters.grain_texture) {
  75629. _this._grainTexture = parameters.grain_texture;
  75630. }
  75631. else {
  75632. _this._createGrainTexture();
  75633. }
  75634. // save parameters
  75635. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  75636. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  75637. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  75638. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  75639. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  75640. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  75641. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  75642. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  75643. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  75644. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  75645. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  75646. // Create effects
  75647. _this._createChromaticAberrationPostProcess(ratio);
  75648. _this._createHighlightsPostProcess(ratio);
  75649. _this._createDepthOfFieldPostProcess(ratio / 4);
  75650. // Set up pipeline
  75651. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  75652. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  75653. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  75654. if (_this._highlightsGain === -1) {
  75655. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  75656. }
  75657. // Finish
  75658. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75659. if (cameras) {
  75660. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75661. }
  75662. return _this;
  75663. }
  75664. // public methods (self explanatory)
  75665. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  75666. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  75667. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  75668. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  75669. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  75670. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  75671. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  75672. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  75673. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  75674. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  75675. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  75676. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  75677. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  75678. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  75679. };
  75680. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  75681. this._highlightsPostProcess.updateEffect();
  75682. };
  75683. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  75684. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  75685. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  75686. this._highlightsGain = amount;
  75687. };
  75688. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  75689. if (this._highlightsGain === -1) {
  75690. this._highlightsGain = 1.0;
  75691. }
  75692. this._highlightsThreshold = amount;
  75693. };
  75694. LensRenderingPipeline.prototype.disableHighlights = function () {
  75695. this._highlightsGain = -1;
  75696. };
  75697. /**
  75698. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  75699. */
  75700. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75701. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75702. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75703. this._chromaticAberrationPostProcess = null;
  75704. this._highlightsPostProcess = null;
  75705. this._depthOfFieldPostProcess = null;
  75706. this._grainTexture.dispose();
  75707. if (disableDepthRender)
  75708. this._scene.disableDepthRenderer();
  75709. };
  75710. // colors shifting and distortion
  75711. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  75712. var _this = this;
  75713. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  75714. [], // samplers
  75715. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75716. this._chromaticAberrationPostProcess.onApply = function (effect) {
  75717. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  75718. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75719. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75720. effect.setFloat('radialIntensity', 1);
  75721. effect.setFloat2('direction', 17, 17);
  75722. effect.setFloat2('centerPosition', 0.5, 0.5);
  75723. };
  75724. };
  75725. // highlights enhancing
  75726. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  75727. var _this = this;
  75728. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  75729. [], // samplers
  75730. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  75731. this._highlightsPostProcess.onApply = function (effect) {
  75732. effect.setFloat('gain', _this._highlightsGain);
  75733. effect.setFloat('threshold', _this._highlightsThreshold);
  75734. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  75735. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75736. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75737. };
  75738. };
  75739. // colors shifting and distortion
  75740. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  75741. var _this = this;
  75742. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  75743. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  75744. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  75745. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75746. this._depthOfFieldPostProcess.onApply = function (effect) {
  75747. effect.setTexture("depthSampler", _this._depthTexture);
  75748. effect.setTexture("grainSampler", _this._grainTexture);
  75749. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  75750. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  75751. effect.setFloat('grain_amount', _this._grainAmount);
  75752. effect.setBool('blur_noise', _this._blurNoise);
  75753. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75754. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75755. effect.setFloat('distortion', _this._distortion);
  75756. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  75757. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  75758. effect.setFloat('aperture', _this._dofAperture);
  75759. effect.setFloat('darken', _this._dofDarken);
  75760. effect.setFloat('edge_blur', _this._edgeBlur);
  75761. effect.setBool('highlights', (_this._highlightsGain !== -1));
  75762. if (_this._scene.activeCamera) {
  75763. effect.setFloat('near', _this._scene.activeCamera.minZ);
  75764. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  75765. }
  75766. };
  75767. };
  75768. // creates a black and white random noise texture, 512x512
  75769. LensRenderingPipeline.prototype._createGrainTexture = function () {
  75770. var size = 512;
  75771. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75772. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75773. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75774. var context = this._grainTexture.getContext();
  75775. var rand = function (min, max) {
  75776. return Math.random() * (max - min) + min;
  75777. };
  75778. var value;
  75779. for (var x = 0; x < size; x++) {
  75780. for (var y = 0; y < size; y++) {
  75781. value = Math.floor(rand(0.42, 0.58) * 255);
  75782. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  75783. context.fillRect(x, y, 1, 1);
  75784. }
  75785. }
  75786. this._grainTexture.update(false);
  75787. };
  75788. return LensRenderingPipeline;
  75789. }(BABYLON.PostProcessRenderPipeline));
  75790. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  75791. })(BABYLON || (BABYLON = {}));
  75792. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  75793. var BABYLON;
  75794. (function (BABYLON) {
  75795. var StandardRenderingPipeline = /** @class */ (function (_super) {
  75796. __extends(StandardRenderingPipeline, _super);
  75797. /**
  75798. * @constructor
  75799. * @param {string} name - The rendering pipeline name
  75800. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75801. * @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)
  75802. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  75803. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75804. */
  75805. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  75806. if (originalPostProcess === void 0) { originalPostProcess = null; }
  75807. var _this = _super.call(this, scene.getEngine(), name) || this;
  75808. _this.downSampleX4PostProcess = null;
  75809. _this.brightPassPostProcess = null;
  75810. _this.blurHPostProcesses = [];
  75811. _this.blurVPostProcesses = [];
  75812. _this.textureAdderPostProcess = null;
  75813. _this.volumetricLightPostProcess = null;
  75814. _this.volumetricLightSmoothXPostProcess = null;
  75815. _this.volumetricLightSmoothYPostProcess = null;
  75816. _this.volumetricLightMergePostProces = null;
  75817. _this.volumetricLightFinalPostProcess = null;
  75818. _this.luminancePostProcess = null;
  75819. _this.luminanceDownSamplePostProcesses = [];
  75820. _this.hdrPostProcess = null;
  75821. _this.textureAdderFinalPostProcess = null;
  75822. _this.lensFlareFinalPostProcess = null;
  75823. _this.hdrFinalPostProcess = null;
  75824. _this.lensFlarePostProcess = null;
  75825. _this.lensFlareComposePostProcess = null;
  75826. _this.motionBlurPostProcess = null;
  75827. _this.depthOfFieldPostProcess = null;
  75828. // Values
  75829. _this.brightThreshold = 1.0;
  75830. _this.blurWidth = 512.0;
  75831. _this.horizontalBlur = false;
  75832. _this.exposure = 1.0;
  75833. _this.lensTexture = null;
  75834. _this.volumetricLightCoefficient = 0.2;
  75835. _this.volumetricLightPower = 4.0;
  75836. _this.volumetricLightBlurScale = 64.0;
  75837. _this.sourceLight = null;
  75838. _this.hdrMinimumLuminance = 1.0;
  75839. _this.hdrDecreaseRate = 0.5;
  75840. _this.hdrIncreaseRate = 0.5;
  75841. _this.lensColorTexture = null;
  75842. _this.lensFlareStrength = 20.0;
  75843. _this.lensFlareGhostDispersal = 1.4;
  75844. _this.lensFlareHaloWidth = 0.7;
  75845. _this.lensFlareDistortionStrength = 16.0;
  75846. _this.lensStarTexture = null;
  75847. _this.lensFlareDirtTexture = null;
  75848. _this.depthOfFieldDistance = 10.0;
  75849. _this.depthOfFieldBlurWidth = 64.0;
  75850. _this.motionStrength = 1.0;
  75851. // IAnimatable
  75852. _this.animations = [];
  75853. _this._currentDepthOfFieldSource = null;
  75854. _this._hdrCurrentLuminance = 1.0;
  75855. // Getters and setters
  75856. _this._bloomEnabled = true;
  75857. _this._depthOfFieldEnabled = false;
  75858. _this._vlsEnabled = false;
  75859. _this._lensFlareEnabled = false;
  75860. _this._hdrEnabled = false;
  75861. _this._motionBlurEnabled = false;
  75862. _this._motionBlurSamples = 64.0;
  75863. _this._volumetricLightStepsCount = 50.0;
  75864. _this._cameras = cameras || [];
  75865. // Initialize
  75866. _this._scene = scene;
  75867. _this._basePostProcess = originalPostProcess;
  75868. _this._ratio = ratio;
  75869. // Misc
  75870. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75871. // Finish
  75872. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75873. _this._buildPipeline();
  75874. return _this;
  75875. }
  75876. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  75877. get: function () {
  75878. return this._bloomEnabled;
  75879. },
  75880. set: function (enabled) {
  75881. if (this._bloomEnabled === enabled) {
  75882. return;
  75883. }
  75884. this._bloomEnabled = enabled;
  75885. this._buildPipeline();
  75886. },
  75887. enumerable: true,
  75888. configurable: true
  75889. });
  75890. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  75891. get: function () {
  75892. return this._depthOfFieldEnabled;
  75893. },
  75894. set: function (enabled) {
  75895. if (this._depthOfFieldEnabled === enabled) {
  75896. return;
  75897. }
  75898. this._depthOfFieldEnabled = enabled;
  75899. this._buildPipeline();
  75900. },
  75901. enumerable: true,
  75902. configurable: true
  75903. });
  75904. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  75905. get: function () {
  75906. return this._lensFlareEnabled;
  75907. },
  75908. set: function (enabled) {
  75909. if (this._lensFlareEnabled === enabled) {
  75910. return;
  75911. }
  75912. this._lensFlareEnabled = enabled;
  75913. this._buildPipeline();
  75914. },
  75915. enumerable: true,
  75916. configurable: true
  75917. });
  75918. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  75919. get: function () {
  75920. return this._hdrEnabled;
  75921. },
  75922. set: function (enabled) {
  75923. if (this._hdrEnabled === enabled) {
  75924. return;
  75925. }
  75926. this._hdrEnabled = enabled;
  75927. this._buildPipeline();
  75928. },
  75929. enumerable: true,
  75930. configurable: true
  75931. });
  75932. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  75933. get: function () {
  75934. return this._vlsEnabled;
  75935. },
  75936. set: function (enabled) {
  75937. if (this._vlsEnabled === enabled) {
  75938. return;
  75939. }
  75940. if (enabled) {
  75941. var geometry = this._scene.enableGeometryBufferRenderer();
  75942. if (!geometry) {
  75943. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  75944. return;
  75945. }
  75946. }
  75947. this._vlsEnabled = enabled;
  75948. this._buildPipeline();
  75949. },
  75950. enumerable: true,
  75951. configurable: true
  75952. });
  75953. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  75954. get: function () {
  75955. return this._motionBlurEnabled;
  75956. },
  75957. set: function (enabled) {
  75958. if (this._motionBlurEnabled === enabled) {
  75959. return;
  75960. }
  75961. this._motionBlurEnabled = enabled;
  75962. this._buildPipeline();
  75963. },
  75964. enumerable: true,
  75965. configurable: true
  75966. });
  75967. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  75968. get: function () {
  75969. return this._volumetricLightStepsCount;
  75970. },
  75971. set: function (count) {
  75972. if (this.volumetricLightPostProcess) {
  75973. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  75974. }
  75975. this._volumetricLightStepsCount = count;
  75976. },
  75977. enumerable: true,
  75978. configurable: true
  75979. });
  75980. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  75981. get: function () {
  75982. return this._motionBlurSamples;
  75983. },
  75984. set: function (samples) {
  75985. if (this.motionBlurPostProcess) {
  75986. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  75987. }
  75988. this._motionBlurSamples = samples;
  75989. },
  75990. enumerable: true,
  75991. configurable: true
  75992. });
  75993. StandardRenderingPipeline.prototype._buildPipeline = function () {
  75994. var _this = this;
  75995. var ratio = this._ratio;
  75996. var scene = this._scene;
  75997. this._disposePostProcesses();
  75998. this._reset();
  75999. // Create pass post-process
  76000. if (!this._basePostProcess) {
  76001. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  76002. this.originalPostProcess.onApply = function (effect) {
  76003. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  76004. };
  76005. }
  76006. else {
  76007. this.originalPostProcess = this._basePostProcess;
  76008. }
  76009. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  76010. this._currentDepthOfFieldSource = this.originalPostProcess;
  76011. if (this._bloomEnabled) {
  76012. // Create down sample X4 post-process
  76013. this._createDownSampleX4PostProcess(scene, ratio / 2);
  76014. // Create bright pass post-process
  76015. this._createBrightPassPostProcess(scene, ratio / 2);
  76016. // Create gaussian blur post-processes (down sampling blurs)
  76017. this._createBlurPostProcesses(scene, ratio / 4, 1);
  76018. // Create texture adder post-process
  76019. this._createTextureAdderPostProcess(scene, ratio);
  76020. // Create depth-of-field source post-process
  76021. 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);
  76022. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  76023. }
  76024. if (this._vlsEnabled) {
  76025. // Create volumetric light
  76026. this._createVolumetricLightPostProcess(scene, ratio);
  76027. // Create volumetric light final post-process
  76028. 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);
  76029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  76030. }
  76031. if (this._lensFlareEnabled) {
  76032. // Create lens flare post-process
  76033. this._createLensFlarePostProcess(scene, ratio);
  76034. // Create depth-of-field source post-process post lens-flare and disable it now
  76035. 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);
  76036. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  76037. }
  76038. if (this._hdrEnabled) {
  76039. // Create luminance
  76040. this._createLuminancePostProcesses(scene, this._floatTextureType);
  76041. // Create HDR
  76042. this._createHdrPostProcess(scene, ratio);
  76043. // Create depth-of-field source post-process post hdr and disable it now
  76044. 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);
  76045. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  76046. }
  76047. if (this._depthOfFieldEnabled) {
  76048. // Create gaussian blur used by depth-of-field
  76049. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  76050. // Create depth-of-field post-process
  76051. this._createDepthOfFieldPostProcess(scene, ratio);
  76052. }
  76053. if (this._motionBlurEnabled) {
  76054. // Create motion blur post-process
  76055. this._createMotionBlurPostProcess(scene, ratio);
  76056. }
  76057. if (this._cameras !== null) {
  76058. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76059. }
  76060. };
  76061. // Down Sample X4 Post-Processs
  76062. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  76063. var _this = this;
  76064. var downSampleX4Offsets = new Array(32);
  76065. 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);
  76066. this.downSampleX4PostProcess.onApply = function (effect) {
  76067. var id = 0;
  76068. var width = _this.downSampleX4PostProcess.width;
  76069. var height = _this.downSampleX4PostProcess.height;
  76070. for (var i = -2; i < 2; i++) {
  76071. for (var j = -2; j < 2; j++) {
  76072. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  76073. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  76074. id += 2;
  76075. }
  76076. }
  76077. effect.setArray2("dsOffsets", downSampleX4Offsets);
  76078. };
  76079. // Add to pipeline
  76080. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  76081. };
  76082. // Brightpass Post-Process
  76083. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  76084. var _this = this;
  76085. var brightOffsets = new Array(8);
  76086. 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);
  76087. this.brightPassPostProcess.onApply = function (effect) {
  76088. var sU = (1.0 / _this.brightPassPostProcess.width);
  76089. var sV = (1.0 / _this.brightPassPostProcess.height);
  76090. brightOffsets[0] = -0.5 * sU;
  76091. brightOffsets[1] = 0.5 * sV;
  76092. brightOffsets[2] = 0.5 * sU;
  76093. brightOffsets[3] = 0.5 * sV;
  76094. brightOffsets[4] = -0.5 * sU;
  76095. brightOffsets[5] = -0.5 * sV;
  76096. brightOffsets[6] = 0.5 * sU;
  76097. brightOffsets[7] = -0.5 * sV;
  76098. effect.setArray2("dsOffsets", brightOffsets);
  76099. effect.setFloat("brightThreshold", _this.brightThreshold);
  76100. };
  76101. // Add to pipeline
  76102. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  76103. };
  76104. // Create blur H&V post-processes
  76105. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  76106. var _this = this;
  76107. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  76108. var engine = scene.getEngine();
  76109. 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);
  76110. 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);
  76111. blurX.onActivateObservable.add(function () {
  76112. var dw = blurX.width / engine.getRenderWidth();
  76113. blurX.kernel = _this[blurWidthKey] * dw;
  76114. });
  76115. blurY.onActivateObservable.add(function () {
  76116. var dw = blurY.height / engine.getRenderHeight();
  76117. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  76118. });
  76119. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  76120. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  76121. this.blurHPostProcesses.push(blurX);
  76122. this.blurVPostProcesses.push(blurY);
  76123. };
  76124. // Create texture adder post-process
  76125. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  76126. var _this = this;
  76127. 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);
  76128. this.textureAdderPostProcess.onApply = function (effect) {
  76129. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  76130. effect.setTexture("lensSampler", _this.lensTexture);
  76131. effect.setFloat("exposure", _this.exposure);
  76132. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  76133. };
  76134. // Add to pipeline
  76135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  76136. };
  76137. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  76138. var _this = this;
  76139. var geometryRenderer = scene.enableGeometryBufferRenderer();
  76140. geometryRenderer.enablePosition = true;
  76141. var geometry = geometryRenderer.getGBuffer();
  76142. // Base post-process
  76143. 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));
  76144. var depthValues = BABYLON.Vector2.Zero();
  76145. this.volumetricLightPostProcess.onApply = function (effect) {
  76146. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  76147. var generator = _this.sourceLight.getShadowGenerator();
  76148. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  76149. effect.setTexture("positionSampler", geometry.textures[2]);
  76150. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  76151. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  76152. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  76153. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  76154. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  76155. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  76156. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  76157. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  76158. effect.setVector2("depthValues", depthValues);
  76159. }
  76160. };
  76161. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  76162. // Smooth
  76163. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  76164. // Merge
  76165. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  76166. this.volumetricLightMergePostProces.onApply = function (effect) {
  76167. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  76168. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  76169. };
  76170. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  76171. };
  76172. // Create luminance
  76173. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  76174. var _this = this;
  76175. // Create luminance
  76176. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  76177. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  76178. var offsets = [];
  76179. this.luminancePostProcess.onApply = function (effect) {
  76180. var sU = (1.0 / _this.luminancePostProcess.width);
  76181. var sV = (1.0 / _this.luminancePostProcess.height);
  76182. offsets[0] = -0.5 * sU;
  76183. offsets[1] = 0.5 * sV;
  76184. offsets[2] = 0.5 * sU;
  76185. offsets[3] = 0.5 * sV;
  76186. offsets[4] = -0.5 * sU;
  76187. offsets[5] = -0.5 * sV;
  76188. offsets[6] = 0.5 * sU;
  76189. offsets[7] = -0.5 * sV;
  76190. effect.setArray2("lumOffsets", offsets);
  76191. };
  76192. // Add to pipeline
  76193. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  76194. // Create down sample luminance
  76195. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  76196. var size = Math.pow(3, i);
  76197. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  76198. if (i === 0) {
  76199. defines += "#define FINAL_DOWN_SAMPLER";
  76200. }
  76201. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  76202. this.luminanceDownSamplePostProcesses.push(postProcess);
  76203. }
  76204. // Create callbacks and add effects
  76205. var lastLuminance = this.luminancePostProcess;
  76206. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  76207. var downSampleOffsets = new Array(18);
  76208. pp.onApply = function (effect) {
  76209. if (!lastLuminance) {
  76210. return;
  76211. }
  76212. var id = 0;
  76213. for (var x = -1; x < 2; x++) {
  76214. for (var y = -1; y < 2; y++) {
  76215. downSampleOffsets[id] = x / lastLuminance.width;
  76216. downSampleOffsets[id + 1] = y / lastLuminance.height;
  76217. id += 2;
  76218. }
  76219. }
  76220. effect.setArray2("dsOffsets", downSampleOffsets);
  76221. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  76222. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76223. lastLuminance = _this.luminancePostProcess;
  76224. }
  76225. else {
  76226. lastLuminance = pp;
  76227. }
  76228. };
  76229. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76230. pp.onAfterRender = function (effect) {
  76231. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  76232. 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);
  76233. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  76234. };
  76235. }
  76236. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  76237. });
  76238. };
  76239. // Create HDR post-process
  76240. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  76241. var _this = this;
  76242. 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);
  76243. var outputLiminance = 1;
  76244. var time = 0;
  76245. var lastTime = 0;
  76246. this.hdrPostProcess.onApply = function (effect) {
  76247. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  76248. time += scene.getEngine().getDeltaTime();
  76249. if (outputLiminance < 0) {
  76250. outputLiminance = _this._hdrCurrentLuminance;
  76251. }
  76252. else {
  76253. var dt = (lastTime - time) / 1000.0;
  76254. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  76255. outputLiminance += _this.hdrDecreaseRate * dt;
  76256. }
  76257. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  76258. outputLiminance -= _this.hdrIncreaseRate * dt;
  76259. }
  76260. else {
  76261. outputLiminance = _this._hdrCurrentLuminance;
  76262. }
  76263. }
  76264. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  76265. effect.setFloat("averageLuminance", outputLiminance);
  76266. lastTime = time;
  76267. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  76268. };
  76269. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  76270. };
  76271. // Create lens flare post-process
  76272. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  76273. var _this = this;
  76274. 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);
  76275. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  76276. this._createBlurPostProcesses(scene, ratio / 4, 2);
  76277. 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);
  76278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  76279. var resolution = new BABYLON.Vector2(0, 0);
  76280. // Lens flare
  76281. this.lensFlarePostProcess.onApply = function (effect) {
  76282. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  76283. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  76284. effect.setFloat("strength", _this.lensFlareStrength);
  76285. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  76286. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  76287. // Shift
  76288. resolution.x = _this.lensFlarePostProcess.width;
  76289. resolution.y = _this.lensFlarePostProcess.height;
  76290. effect.setVector2("resolution", resolution);
  76291. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  76292. };
  76293. // Compose
  76294. 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);
  76295. 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);
  76296. this.lensFlareComposePostProcess.onApply = function (effect) {
  76297. if (!_this._scene.activeCamera) {
  76298. return;
  76299. }
  76300. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76301. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  76302. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  76303. // Lens start rotation matrix
  76304. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  76305. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  76306. 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));
  76307. camRot *= 4.0;
  76308. 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);
  76309. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  76310. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  76311. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  76312. };
  76313. };
  76314. // Create depth-of-field post-process
  76315. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  76316. var _this = this;
  76317. 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);
  76318. this.depthOfFieldPostProcess.onApply = function (effect) {
  76319. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76320. effect.setTexture("depthSampler", _this._getDepthTexture());
  76321. effect.setFloat("distance", _this.depthOfFieldDistance);
  76322. };
  76323. // Add to pipeline
  76324. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  76325. };
  76326. // Create motion blur post-process
  76327. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  76328. var _this = this;
  76329. 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);
  76330. var motionScale = 0;
  76331. var prevViewProjection = BABYLON.Matrix.Identity();
  76332. var invViewProjection = BABYLON.Matrix.Identity();
  76333. var viewProjection = BABYLON.Matrix.Identity();
  76334. var screenSize = BABYLON.Vector2.Zero();
  76335. this.motionBlurPostProcess.onApply = function (effect) {
  76336. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  76337. viewProjection.invertToRef(invViewProjection);
  76338. effect.setMatrix("inverseViewProjection", invViewProjection);
  76339. effect.setMatrix("prevViewProjection", prevViewProjection);
  76340. prevViewProjection = viewProjection;
  76341. screenSize.x = _this.motionBlurPostProcess.width;
  76342. screenSize.y = _this.motionBlurPostProcess.height;
  76343. effect.setVector2("screenSize", screenSize);
  76344. motionScale = scene.getEngine().getFps() / 60.0;
  76345. effect.setFloat("motionScale", motionScale);
  76346. effect.setFloat("motionStrength", _this.motionStrength);
  76347. effect.setTexture("depthSampler", _this._getDepthTexture());
  76348. };
  76349. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  76350. };
  76351. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  76352. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  76353. var renderer = this._scene.enableGeometryBufferRenderer();
  76354. return renderer.getGBuffer().textures[0];
  76355. }
  76356. return this._scene.enableDepthRenderer().getDepthMap();
  76357. };
  76358. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  76359. for (var i = 0; i < this._cameras.length; i++) {
  76360. var camera = this._cameras[i];
  76361. if (this.originalPostProcess) {
  76362. this.originalPostProcess.dispose(camera);
  76363. }
  76364. if (this.downSampleX4PostProcess) {
  76365. this.downSampleX4PostProcess.dispose(camera);
  76366. }
  76367. if (this.brightPassPostProcess) {
  76368. this.brightPassPostProcess.dispose(camera);
  76369. }
  76370. if (this.textureAdderPostProcess) {
  76371. this.textureAdderPostProcess.dispose(camera);
  76372. }
  76373. if (this.textureAdderFinalPostProcess) {
  76374. this.textureAdderFinalPostProcess.dispose(camera);
  76375. }
  76376. if (this.volumetricLightPostProcess) {
  76377. this.volumetricLightPostProcess.dispose(camera);
  76378. }
  76379. if (this.volumetricLightSmoothXPostProcess) {
  76380. this.volumetricLightSmoothXPostProcess.dispose(camera);
  76381. }
  76382. if (this.volumetricLightSmoothYPostProcess) {
  76383. this.volumetricLightSmoothYPostProcess.dispose(camera);
  76384. }
  76385. if (this.volumetricLightMergePostProces) {
  76386. this.volumetricLightMergePostProces.dispose(camera);
  76387. }
  76388. if (this.volumetricLightFinalPostProcess) {
  76389. this.volumetricLightFinalPostProcess.dispose(camera);
  76390. }
  76391. if (this.lensFlarePostProcess) {
  76392. this.lensFlarePostProcess.dispose(camera);
  76393. }
  76394. if (this.lensFlareComposePostProcess) {
  76395. this.lensFlareComposePostProcess.dispose(camera);
  76396. }
  76397. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  76398. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  76399. }
  76400. if (this.luminancePostProcess) {
  76401. this.luminancePostProcess.dispose(camera);
  76402. }
  76403. if (this.hdrPostProcess) {
  76404. this.hdrPostProcess.dispose(camera);
  76405. }
  76406. if (this.hdrFinalPostProcess) {
  76407. this.hdrFinalPostProcess.dispose(camera);
  76408. }
  76409. if (this.depthOfFieldPostProcess) {
  76410. this.depthOfFieldPostProcess.dispose(camera);
  76411. }
  76412. if (this.motionBlurPostProcess) {
  76413. this.motionBlurPostProcess.dispose(camera);
  76414. }
  76415. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  76416. this.blurHPostProcesses[j].dispose(camera);
  76417. }
  76418. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  76419. this.blurVPostProcesses[j].dispose(camera);
  76420. }
  76421. }
  76422. this.originalPostProcess = null;
  76423. this.downSampleX4PostProcess = null;
  76424. this.brightPassPostProcess = null;
  76425. this.textureAdderPostProcess = null;
  76426. this.textureAdderFinalPostProcess = null;
  76427. this.volumetricLightPostProcess = null;
  76428. this.volumetricLightSmoothXPostProcess = null;
  76429. this.volumetricLightSmoothYPostProcess = null;
  76430. this.volumetricLightMergePostProces = null;
  76431. this.volumetricLightFinalPostProcess = null;
  76432. this.lensFlarePostProcess = null;
  76433. this.lensFlareComposePostProcess = null;
  76434. this.luminancePostProcess = null;
  76435. this.hdrPostProcess = null;
  76436. this.hdrFinalPostProcess = null;
  76437. this.depthOfFieldPostProcess = null;
  76438. this.motionBlurPostProcess = null;
  76439. this.luminanceDownSamplePostProcesses = [];
  76440. this.blurHPostProcesses = [];
  76441. this.blurVPostProcesses = [];
  76442. };
  76443. /**
  76444. * Dispose of the pipeline and stop all post processes
  76445. */
  76446. StandardRenderingPipeline.prototype.dispose = function () {
  76447. this._disposePostProcesses();
  76448. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76449. _super.prototype.dispose.call(this);
  76450. };
  76451. /**
  76452. * Serialize the rendering pipeline (Used when exporting)
  76453. * @returns the serialized object
  76454. */
  76455. StandardRenderingPipeline.prototype.serialize = function () {
  76456. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76457. if (this.sourceLight) {
  76458. serializationObject.sourceLightId = this.sourceLight.id;
  76459. }
  76460. serializationObject.customType = "StandardRenderingPipeline";
  76461. return serializationObject;
  76462. };
  76463. /**
  76464. * Parse the serialized pipeline
  76465. * @param source Source pipeline.
  76466. * @param scene The scene to load the pipeline to.
  76467. * @param rootUrl The URL of the serialized pipeline.
  76468. * @returns An instantiated pipeline from the serialized object.
  76469. */
  76470. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76471. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76472. if (source.sourceLightId) {
  76473. p.sourceLight = scene.getLightByID(source.sourceLightId);
  76474. }
  76475. return p;
  76476. };
  76477. // Luminance steps
  76478. StandardRenderingPipeline.LuminanceSteps = 6;
  76479. __decorate([
  76480. BABYLON.serialize()
  76481. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  76482. __decorate([
  76483. BABYLON.serialize()
  76484. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  76485. __decorate([
  76486. BABYLON.serialize()
  76487. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  76488. __decorate([
  76489. BABYLON.serialize()
  76490. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  76491. __decorate([
  76492. BABYLON.serializeAsTexture("lensTexture")
  76493. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  76494. __decorate([
  76495. BABYLON.serialize()
  76496. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  76497. __decorate([
  76498. BABYLON.serialize()
  76499. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  76500. __decorate([
  76501. BABYLON.serialize()
  76502. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  76503. __decorate([
  76504. BABYLON.serialize()
  76505. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  76506. __decorate([
  76507. BABYLON.serialize()
  76508. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  76509. __decorate([
  76510. BABYLON.serialize()
  76511. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  76512. __decorate([
  76513. BABYLON.serializeAsTexture("lensColorTexture")
  76514. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  76515. __decorate([
  76516. BABYLON.serialize()
  76517. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  76518. __decorate([
  76519. BABYLON.serialize()
  76520. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  76521. __decorate([
  76522. BABYLON.serialize()
  76523. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  76524. __decorate([
  76525. BABYLON.serialize()
  76526. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  76527. __decorate([
  76528. BABYLON.serializeAsTexture("lensStarTexture")
  76529. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  76530. __decorate([
  76531. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  76532. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  76533. __decorate([
  76534. BABYLON.serialize()
  76535. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  76536. __decorate([
  76537. BABYLON.serialize()
  76538. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  76539. __decorate([
  76540. BABYLON.serialize()
  76541. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  76542. __decorate([
  76543. BABYLON.serialize()
  76544. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  76545. __decorate([
  76546. BABYLON.serialize()
  76547. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  76548. __decorate([
  76549. BABYLON.serialize()
  76550. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  76551. __decorate([
  76552. BABYLON.serialize()
  76553. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  76554. __decorate([
  76555. BABYLON.serialize()
  76556. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  76557. __decorate([
  76558. BABYLON.serialize()
  76559. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  76560. __decorate([
  76561. BABYLON.serialize()
  76562. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  76563. __decorate([
  76564. BABYLON.serialize()
  76565. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  76566. __decorate([
  76567. BABYLON.serialize()
  76568. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  76569. return StandardRenderingPipeline;
  76570. }(BABYLON.PostProcessRenderPipeline));
  76571. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  76572. })(BABYLON || (BABYLON = {}));
  76573. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  76574. var BABYLON;
  76575. (function (BABYLON) {
  76576. var FxaaPostProcess = /** @class */ (function (_super) {
  76577. __extends(FxaaPostProcess, _super);
  76578. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76579. if (camera === void 0) { camera = null; }
  76580. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76581. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  76582. var defines = _this._getDefines();
  76583. _this.updateEffect(defines);
  76584. _this.onApplyObservable.add(function (effect) {
  76585. var texelSize = _this.texelSize;
  76586. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  76587. });
  76588. return _this;
  76589. }
  76590. FxaaPostProcess.prototype._getDefines = function () {
  76591. var engine = this.getEngine();
  76592. if (!engine) {
  76593. return null;
  76594. }
  76595. var glInfo = engine.getGlInfo();
  76596. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  76597. return "#define MALI 1\n";
  76598. }
  76599. return null;
  76600. };
  76601. return FxaaPostProcess;
  76602. }(BABYLON.PostProcess));
  76603. BABYLON.FxaaPostProcess = FxaaPostProcess;
  76604. })(BABYLON || (BABYLON = {}));
  76605. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  76606. var BABYLON;
  76607. (function (BABYLON) {
  76608. /**
  76609. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  76610. */
  76611. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  76612. __extends(ChromaticAberrationPostProcess, _super);
  76613. /**
  76614. * Creates a new instance ChromaticAberrationPostProcess
  76615. * @param name The name of the effect.
  76616. * @param screenWidth The width of the screen to apply the effect on.
  76617. * @param screenHeight The height of the screen to apply the effect on.
  76618. * @param options The required width/height ratio to downsize to before computing the render pass.
  76619. * @param camera The camera to apply the render pass to.
  76620. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76621. * @param engine The engine which the post process will be applied. (default: current engine)
  76622. * @param reusable If the post process can be reused on the same frame. (default: false)
  76623. * @param textureType Type of textures used when performing the post process. (default: 0)
  76624. * @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)
  76625. */
  76626. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76627. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76628. if (blockCompilation === void 0) { blockCompilation = false; }
  76629. 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;
  76630. /**
  76631. * The amount of seperation of rgb channels (default: 30)
  76632. */
  76633. _this.aberrationAmount = 30;
  76634. /**
  76635. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  76636. */
  76637. _this.radialIntensity = 0;
  76638. /**
  76639. * 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))
  76640. */
  76641. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  76642. /**
  76643. * 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))
  76644. */
  76645. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  76646. _this.onApplyObservable.add(function (effect) {
  76647. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  76648. effect.setFloat('screen_width', screenWidth);
  76649. effect.setFloat('screen_height', screenHeight);
  76650. effect.setFloat('radialIntensity', _this.radialIntensity);
  76651. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  76652. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  76653. });
  76654. return _this;
  76655. }
  76656. return ChromaticAberrationPostProcess;
  76657. }(BABYLON.PostProcess));
  76658. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  76659. })(BABYLON || (BABYLON = {}));
  76660. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  76661. var BABYLON;
  76662. (function (BABYLON) {
  76663. /**
  76664. * The GrainPostProcess adds noise to the image at mid luminance levels
  76665. */
  76666. var GrainPostProcess = /** @class */ (function (_super) {
  76667. __extends(GrainPostProcess, _super);
  76668. /**
  76669. * Creates a new instance of @see GrainPostProcess
  76670. * @param name The name of the effect.
  76671. * @param options The required width/height ratio to downsize to before computing the render pass.
  76672. * @param camera The camera to apply the render pass to.
  76673. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76674. * @param engine The engine which the post process will be applied. (default: current engine)
  76675. * @param reusable If the post process can be reused on the same frame. (default: false)
  76676. * @param textureType Type of textures used when performing the post process. (default: 0)
  76677. * @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)
  76678. */
  76679. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76680. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76681. if (blockCompilation === void 0) { blockCompilation = false; }
  76682. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76683. /**
  76684. * The intensity of the grain added (default: 30)
  76685. */
  76686. _this.intensity = 30;
  76687. /**
  76688. * If the grain should be randomized on every frame
  76689. */
  76690. _this.animated = false;
  76691. _this.onApplyObservable.add(function (effect) {
  76692. effect.setFloat('intensity', _this.intensity);
  76693. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  76694. });
  76695. return _this;
  76696. }
  76697. return GrainPostProcess;
  76698. }(BABYLON.PostProcess));
  76699. BABYLON.GrainPostProcess = GrainPostProcess;
  76700. })(BABYLON || (BABYLON = {}));
  76701. //# sourceMappingURL=babylon.grainPostProcess.js.map
  76702. var BABYLON;
  76703. (function (BABYLON) {
  76704. /**
  76705. * The SharpenPostProcess applies a sharpen kernel to every pixel
  76706. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76707. */
  76708. var SharpenPostProcess = /** @class */ (function (_super) {
  76709. __extends(SharpenPostProcess, _super);
  76710. /**
  76711. * Creates a new instance ConvolutionPostProcess
  76712. * @param name The name of the effect.
  76713. * @param options The required width/height ratio to downsize to before computing the render pass.
  76714. * @param camera The camera to apply the render pass to.
  76715. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76716. * @param engine The engine which the post process will be applied. (default: current engine)
  76717. * @param reusable If the post process can be reused on the same frame. (default: false)
  76718. * @param textureType Type of textures used when performing the post process. (default: 0)
  76719. * @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)
  76720. */
  76721. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76722. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76723. if (blockCompilation === void 0) { blockCompilation = false; }
  76724. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76725. /**
  76726. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  76727. */
  76728. _this.colorAmount = 1.0;
  76729. /**
  76730. * How much sharpness should be applied (default: 0.3)
  76731. */
  76732. _this.edgeAmount = 0.3;
  76733. _this.onApply = function (effect) {
  76734. effect.setFloat2("screenSize", _this.width, _this.height);
  76735. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  76736. };
  76737. return _this;
  76738. }
  76739. return SharpenPostProcess;
  76740. }(BABYLON.PostProcess));
  76741. BABYLON.SharpenPostProcess = SharpenPostProcess;
  76742. })(BABYLON || (BABYLON = {}));
  76743. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  76744. var BABYLON;
  76745. (function (BABYLON) {
  76746. /**
  76747. * The Blur Post Process which blurs an image based on a kernel and direction.
  76748. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  76749. */
  76750. var BlurPostProcess = /** @class */ (function (_super) {
  76751. __extends(BlurPostProcess, _super);
  76752. /**
  76753. * Creates a new instance BlurPostProcess
  76754. * @param name The name of the effect.
  76755. * @param direction The direction in which to blur the image.
  76756. * @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.
  76757. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  76758. * @param camera The camera to apply the render pass to.
  76759. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76760. * @param engine The engine which the post process will be applied. (default: current engine)
  76761. * @param reusable If the post process can be reused on the same frame. (default: false)
  76762. * @param textureType Type of textures used when performing the post process. (default: 0)
  76763. * @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)
  76764. */
  76765. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  76766. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76767. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76768. if (defines === void 0) { defines = ""; }
  76769. if (blockCompilation === void 0) { blockCompilation = false; }
  76770. 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;
  76771. _this.direction = direction;
  76772. _this.blockCompilation = blockCompilation;
  76773. _this._packedFloat = false;
  76774. _this._staticDefines = "";
  76775. _this._staticDefines = defines;
  76776. _this.onApplyObservable.add(function (effect) {
  76777. if (_this._outputTexture) {
  76778. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  76779. }
  76780. else {
  76781. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  76782. }
  76783. });
  76784. _this.kernel = kernel;
  76785. return _this;
  76786. }
  76787. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  76788. /**
  76789. * Gets the length in pixels of the blur sample region
  76790. */
  76791. get: function () {
  76792. return this._idealKernel;
  76793. },
  76794. /**
  76795. * Sets the length in pixels of the blur sample region
  76796. */
  76797. set: function (v) {
  76798. if (this._idealKernel === v) {
  76799. return;
  76800. }
  76801. v = Math.max(v, 1);
  76802. this._idealKernel = v;
  76803. this._kernel = this._nearestBestKernel(v);
  76804. if (!this.blockCompilation) {
  76805. this._updateParameters();
  76806. }
  76807. },
  76808. enumerable: true,
  76809. configurable: true
  76810. });
  76811. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  76812. /**
  76813. * Gets wether or not the blur is unpacking/repacking floats
  76814. */
  76815. get: function () {
  76816. return this._packedFloat;
  76817. },
  76818. /**
  76819. * Sets wether or not the blur needs to unpack/repack floats
  76820. */
  76821. set: function (v) {
  76822. if (this._packedFloat === v) {
  76823. return;
  76824. }
  76825. this._packedFloat = v;
  76826. if (!this.blockCompilation) {
  76827. this._updateParameters();
  76828. }
  76829. },
  76830. enumerable: true,
  76831. configurable: true
  76832. });
  76833. /**
  76834. * Updates the effect with the current post process compile time values and recompiles the shader.
  76835. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76836. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76837. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76838. * @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
  76839. * @param onCompiled Called when the shader has been compiled.
  76840. * @param onError Called if there is an error when compiling a shader.
  76841. */
  76842. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76843. if (defines === void 0) { defines = null; }
  76844. if (uniforms === void 0) { uniforms = null; }
  76845. if (samplers === void 0) { samplers = null; }
  76846. this._updateParameters(onCompiled, onError);
  76847. };
  76848. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  76849. // Generate sampling offsets and weights
  76850. var N = this._kernel;
  76851. var centerIndex = (N - 1) / 2;
  76852. // Generate Gaussian sampling weights over kernel
  76853. var offsets = [];
  76854. var weights = [];
  76855. var totalWeight = 0;
  76856. for (var i = 0; i < N; i++) {
  76857. var u = i / (N - 1);
  76858. var w = this._gaussianWeight(u * 2.0 - 1);
  76859. offsets[i] = (i - centerIndex);
  76860. weights[i] = w;
  76861. totalWeight += w;
  76862. }
  76863. // Normalize weights
  76864. for (var i = 0; i < weights.length; i++) {
  76865. weights[i] /= totalWeight;
  76866. }
  76867. // Optimize: combine samples to take advantage of hardware linear sampling
  76868. // Walk from left to center, combining pairs (symmetrically)
  76869. var linearSamplingWeights = [];
  76870. var linearSamplingOffsets = [];
  76871. var linearSamplingMap = [];
  76872. for (var i = 0; i <= centerIndex; i += 2) {
  76873. var j = Math.min(i + 1, Math.floor(centerIndex));
  76874. var singleCenterSample = i === j;
  76875. if (singleCenterSample) {
  76876. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76877. }
  76878. else {
  76879. var sharedCell = j === centerIndex;
  76880. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  76881. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  76882. if (offsetLinear === 0) {
  76883. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76884. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  76885. }
  76886. else {
  76887. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  76888. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  76889. }
  76890. }
  76891. }
  76892. for (var i = 0; i < linearSamplingMap.length; i++) {
  76893. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  76894. linearSamplingWeights[i] = linearSamplingMap[i].w;
  76895. }
  76896. // Replace with optimized
  76897. offsets = linearSamplingOffsets;
  76898. weights = linearSamplingWeights;
  76899. // Generate shaders
  76900. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  76901. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  76902. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  76903. var defines = "";
  76904. defines += this._staticDefines;
  76905. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  76906. if (this._staticDefines.indexOf("DOF") != -1) {
  76907. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  76908. varyingCount--;
  76909. }
  76910. for (var i = 0; i < varyingCount; i++) {
  76911. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  76912. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  76913. }
  76914. var depCount = 0;
  76915. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  76916. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  76917. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  76918. depCount++;
  76919. }
  76920. if (this.packedFloat) {
  76921. defines += "#define PACKEDFLOAT 1";
  76922. }
  76923. this.blockCompilation = false;
  76924. _super.prototype.updateEffect.call(this, defines, null, null, {
  76925. varyingCount: varyingCount,
  76926. depCount: depCount
  76927. }, onCompiled, onError);
  76928. };
  76929. /**
  76930. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  76931. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  76932. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  76933. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  76934. * The gaps between physical kernels are compensated for in the weighting of the samples
  76935. * @param idealKernel Ideal blur kernel.
  76936. * @return Nearest best kernel.
  76937. */
  76938. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  76939. var v = Math.round(idealKernel);
  76940. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  76941. var k = _a[_i];
  76942. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  76943. return Math.max(k, 3);
  76944. }
  76945. }
  76946. return Math.max(v, 3);
  76947. };
  76948. /**
  76949. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  76950. * @param x The point on the Gaussian distribution to sample.
  76951. * @return the value of the Gaussian function at x.
  76952. */
  76953. BlurPostProcess.prototype._gaussianWeight = function (x) {
  76954. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  76955. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  76956. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  76957. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  76958. // truncated at around 1.3% of peak strength.
  76959. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  76960. var sigma = (1 / 3);
  76961. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  76962. var exponent = -((x * x) / (2.0 * sigma * sigma));
  76963. var weight = (1.0 / denominator) * Math.exp(exponent);
  76964. return weight;
  76965. };
  76966. /**
  76967. * Generates a string that can be used as a floating point number in GLSL.
  76968. * @param x Value to print.
  76969. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  76970. * @return GLSL float string.
  76971. */
  76972. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  76973. if (decimalFigures === void 0) { decimalFigures = 8; }
  76974. return x.toFixed(decimalFigures).replace(/0+$/, '');
  76975. };
  76976. return BlurPostProcess;
  76977. }(BABYLON.PostProcess));
  76978. BABYLON.BlurPostProcess = BlurPostProcess;
  76979. })(BABYLON || (BABYLON = {}));
  76980. //# sourceMappingURL=babylon.blurPostProcess.js.map
  76981. var BABYLON;
  76982. (function (BABYLON) {
  76983. /**
  76984. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  76985. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  76986. * based on samples that have a large difference in distance than the center pixel.
  76987. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76988. */
  76989. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  76990. __extends(DepthOfFieldBlurPostProcess, _super);
  76991. /**
  76992. * Creates a new instance CircleOfConfusionPostProcess
  76993. * @param name The name of the effect.
  76994. * @param scene The scene the effect belongs to.
  76995. * @param direction The direction the blur should be applied.
  76996. * @param kernel The size of the kernel used to blur.
  76997. * @param options The required width/height ratio to downsize to before computing the render pass.
  76998. * @param camera The camera to apply the render pass to.
  76999. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  77000. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  77001. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77002. * @param engine The engine which the post process will be applied. (default: current engine)
  77003. * @param reusable If the post process can be reused on the same frame. (default: false)
  77004. * @param textureType Type of textures used when performing the post process. (default: 0)
  77005. * @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)
  77006. */
  77007. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  77008. if (imageToBlur === void 0) { imageToBlur = null; }
  77009. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77010. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77011. if (blockCompilation === void 0) { blockCompilation = false; }
  77012. 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;
  77013. _this.direction = direction;
  77014. _this.onApplyObservable.add(function (effect) {
  77015. if (imageToBlur != null) {
  77016. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  77017. }
  77018. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77019. if (scene.activeCamera) {
  77020. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  77021. }
  77022. });
  77023. return _this;
  77024. }
  77025. return DepthOfFieldBlurPostProcess;
  77026. }(BABYLON.BlurPostProcess));
  77027. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  77028. })(BABYLON || (BABYLON = {}));
  77029. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  77030. var BABYLON;
  77031. (function (BABYLON) {
  77032. /**
  77033. * Options to be set when merging outputs from the default pipeline.
  77034. */
  77035. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  77036. function DepthOfFieldMergePostProcessOptions() {
  77037. }
  77038. return DepthOfFieldMergePostProcessOptions;
  77039. }());
  77040. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  77041. /**
  77042. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77043. */
  77044. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  77045. __extends(DepthOfFieldMergePostProcess, _super);
  77046. /**
  77047. * Creates a new instance of DepthOfFieldMergePostProcess
  77048. * @param name The name of the effect.
  77049. * @param originalFromInput Post process which's input will be used for the merge.
  77050. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  77051. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  77052. * @param options The required width/height ratio to downsize to before computing the render pass.
  77053. * @param camera The camera to apply the render pass to.
  77054. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77055. * @param engine The engine which the post process will be applied. (default: current engine)
  77056. * @param reusable If the post process can be reused on the same frame. (default: false)
  77057. * @param textureType Type of textures used when performing the post process. (default: 0)
  77058. * @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)
  77059. */
  77060. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77061. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77062. if (blockCompilation === void 0) { blockCompilation = false; }
  77063. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77064. _this.blurSteps = blurSteps;
  77065. _this.onApplyObservable.add(function (effect) {
  77066. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77067. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77068. blurSteps.forEach(function (step, index) {
  77069. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  77070. });
  77071. });
  77072. if (!blockCompilation) {
  77073. _this.updateEffect();
  77074. }
  77075. return _this;
  77076. }
  77077. /**
  77078. * Updates the effect with the current post process compile time values and recompiles the shader.
  77079. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77080. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77081. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77082. * @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
  77083. * @param onCompiled Called when the shader has been compiled.
  77084. * @param onError Called if there is an error when compiling a shader.
  77085. */
  77086. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77087. if (defines === void 0) { defines = null; }
  77088. if (uniforms === void 0) { uniforms = null; }
  77089. if (samplers === void 0) { samplers = null; }
  77090. if (!defines) {
  77091. defines = "";
  77092. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  77093. }
  77094. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  77095. };
  77096. return DepthOfFieldMergePostProcess;
  77097. }(BABYLON.PostProcess));
  77098. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  77099. })(BABYLON || (BABYLON = {}));
  77100. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  77101. var BABYLON;
  77102. (function (BABYLON) {
  77103. /**
  77104. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  77105. */
  77106. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  77107. __extends(CircleOfConfusionPostProcess, _super);
  77108. /**
  77109. * Creates a new instance CircleOfConfusionPostProcess
  77110. * @param name The name of the effect.
  77111. * @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.
  77112. * @param options The required width/height ratio to downsize to before computing the render pass.
  77113. * @param camera The camera to apply the render pass to.
  77114. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77115. * @param engine The engine which the post process will be applied. (default: current engine)
  77116. * @param reusable If the post process can be reused on the same frame. (default: false)
  77117. * @param textureType Type of textures used when performing the post process. (default: 0)
  77118. * @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)
  77119. */
  77120. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77121. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77122. if (blockCompilation === void 0) { blockCompilation = false; }
  77123. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77124. /**
  77125. * 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.
  77126. */
  77127. _this.lensSize = 50;
  77128. /**
  77129. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77130. */
  77131. _this.fStop = 1.4;
  77132. /**
  77133. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77134. */
  77135. _this.focusDistance = 2000;
  77136. /**
  77137. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  77138. */
  77139. _this.focalLength = 50;
  77140. _this._depthTexture = null;
  77141. _this._depthTexture = depthTexture;
  77142. _this.onApplyObservable.add(function (effect) {
  77143. if (!_this._depthTexture) {
  77144. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  77145. return;
  77146. }
  77147. effect.setTexture("depthSampler", _this._depthTexture);
  77148. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  77149. var aperture = _this.lensSize / _this.fStop;
  77150. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  77151. effect.setFloat('focusDistance', _this.focusDistance);
  77152. effect.setFloat('cocPrecalculation', cocPrecalculation);
  77153. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  77154. });
  77155. return _this;
  77156. }
  77157. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  77158. /**
  77159. * 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.
  77160. */
  77161. set: function (value) {
  77162. this._depthTexture = value;
  77163. },
  77164. enumerable: true,
  77165. configurable: true
  77166. });
  77167. return CircleOfConfusionPostProcess;
  77168. }(BABYLON.PostProcess));
  77169. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  77170. })(BABYLON || (BABYLON = {}));
  77171. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  77172. var BABYLON;
  77173. (function (BABYLON) {
  77174. /**
  77175. * Specifies the level of max blur that should be applied when using the depth of field effect
  77176. */
  77177. var DepthOfFieldEffectBlurLevel;
  77178. (function (DepthOfFieldEffectBlurLevel) {
  77179. /**
  77180. * Subtle blur
  77181. */
  77182. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  77183. /**
  77184. * Medium blur
  77185. */
  77186. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  77187. /**
  77188. * Large blur
  77189. */
  77190. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  77191. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  77192. ;
  77193. /**
  77194. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  77195. */
  77196. var DepthOfFieldEffect = /** @class */ (function (_super) {
  77197. __extends(DepthOfFieldEffect, _super);
  77198. /**
  77199. * Creates a new instance DepthOfFieldEffect
  77200. * @param scene The scene the effect belongs to.
  77201. * @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.
  77202. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77203. * @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)
  77204. */
  77205. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  77206. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  77207. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77208. if (blockCompilation === void 0) { blockCompilation = false; }
  77209. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  77210. return _this._effects;
  77211. }, true) || this;
  77212. /**
  77213. * Internal post processes in depth of field effect
  77214. */
  77215. _this._effects = [];
  77216. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  77217. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77218. // 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)
  77219. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  77220. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77221. _this._depthOfFieldBlurY = [];
  77222. _this._depthOfFieldBlurX = [];
  77223. var blurCount = 1;
  77224. var kernelSize = 15;
  77225. switch (blurLevel) {
  77226. case DepthOfFieldEffectBlurLevel.High: {
  77227. blurCount = 3;
  77228. kernelSize = 51;
  77229. break;
  77230. }
  77231. case DepthOfFieldEffectBlurLevel.Medium: {
  77232. blurCount = 2;
  77233. kernelSize = 31;
  77234. break;
  77235. }
  77236. default: {
  77237. kernelSize = 15;
  77238. blurCount = 1;
  77239. break;
  77240. }
  77241. }
  77242. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  77243. var ratio = 1.0;
  77244. for (var i = 0; i < blurCount; i++) {
  77245. 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);
  77246. blurY.autoClear = false;
  77247. ratio = 0.75 / Math.pow(2, i);
  77248. 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);
  77249. blurX.autoClear = false;
  77250. _this._depthOfFieldBlurY.push(blurY);
  77251. _this._depthOfFieldBlurX.push(blurX);
  77252. }
  77253. // Set all post processes on the effect.
  77254. _this._effects = [_this._circleOfConfusion];
  77255. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  77256. _this._effects.push(_this._depthOfFieldBlurY[i]);
  77257. _this._effects.push(_this._depthOfFieldBlurX[i]);
  77258. }
  77259. // Merge blurred images with original image based on circleOfConfusion
  77260. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77261. _this._dofMerge.autoClear = false;
  77262. _this._effects.push(_this._dofMerge);
  77263. return _this;
  77264. }
  77265. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  77266. get: function () {
  77267. return this._circleOfConfusion.focalLength;
  77268. },
  77269. /**
  77270. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  77271. */
  77272. set: function (value) {
  77273. this._circleOfConfusion.focalLength = value;
  77274. },
  77275. enumerable: true,
  77276. configurable: true
  77277. });
  77278. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  77279. get: function () {
  77280. return this._circleOfConfusion.fStop;
  77281. },
  77282. /**
  77283. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77284. */
  77285. set: function (value) {
  77286. this._circleOfConfusion.fStop = value;
  77287. },
  77288. enumerable: true,
  77289. configurable: true
  77290. });
  77291. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  77292. get: function () {
  77293. return this._circleOfConfusion.focusDistance;
  77294. },
  77295. /**
  77296. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77297. */
  77298. set: function (value) {
  77299. this._circleOfConfusion.focusDistance = value;
  77300. },
  77301. enumerable: true,
  77302. configurable: true
  77303. });
  77304. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  77305. get: function () {
  77306. return this._circleOfConfusion.lensSize;
  77307. },
  77308. /**
  77309. * 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.
  77310. */
  77311. set: function (value) {
  77312. this._circleOfConfusion.lensSize = value;
  77313. },
  77314. enumerable: true,
  77315. configurable: true
  77316. });
  77317. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  77318. /**
  77319. * 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.
  77320. */
  77321. set: function (value) {
  77322. this._circleOfConfusion.depthTexture = value;
  77323. },
  77324. enumerable: true,
  77325. configurable: true
  77326. });
  77327. /**
  77328. * Disposes each of the internal effects for a given camera.
  77329. * @param camera The camera to dispose the effect on.
  77330. */
  77331. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  77332. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77333. this._effects[effectIndex].dispose(camera);
  77334. }
  77335. };
  77336. /**
  77337. * Internal
  77338. */
  77339. DepthOfFieldEffect.prototype._updateEffects = function () {
  77340. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77341. this._effects[effectIndex].updateEffect();
  77342. }
  77343. };
  77344. /**
  77345. * Internal
  77346. * @returns if all the contained post processes are ready.
  77347. */
  77348. DepthOfFieldEffect.prototype._isReady = function () {
  77349. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77350. if (!this._effects[effectIndex].isReady()) {
  77351. return false;
  77352. }
  77353. }
  77354. return true;
  77355. };
  77356. return DepthOfFieldEffect;
  77357. }(BABYLON.PostProcessRenderEffect));
  77358. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  77359. })(BABYLON || (BABYLON = {}));
  77360. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  77361. var BABYLON;
  77362. (function (BABYLON) {
  77363. /**
  77364. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77365. */
  77366. var BloomMergePostProcess = /** @class */ (function (_super) {
  77367. __extends(BloomMergePostProcess, _super);
  77368. /**
  77369. * Creates a new instance of @see BloomMergePostProcess
  77370. * @param name The name of the effect.
  77371. * @param originalFromInput Post process which's input will be used for the merge.
  77372. * @param blurred Blurred highlights post process which's output will be used.
  77373. * @param weight Weight of the bloom to be added to the original input.
  77374. * @param options The required width/height ratio to downsize to before computing the render pass.
  77375. * @param camera The camera to apply the render pass to.
  77376. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77377. * @param engine The engine which the post process will be applied. (default: current engine)
  77378. * @param reusable If the post process can be reused on the same frame. (default: false)
  77379. * @param textureType Type of textures used when performing the post process. (default: 0)
  77380. * @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)
  77381. */
  77382. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77383. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77384. if (blockCompilation === void 0) { blockCompilation = false; }
  77385. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77386. _this.weight = weight;
  77387. _this.onApplyObservable.add(function (effect) {
  77388. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77389. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  77390. effect.setFloat("bloomWeight", _this.weight);
  77391. });
  77392. if (!blockCompilation) {
  77393. _this.updateEffect();
  77394. }
  77395. return _this;
  77396. }
  77397. return BloomMergePostProcess;
  77398. }(BABYLON.PostProcess));
  77399. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  77400. })(BABYLON || (BABYLON = {}));
  77401. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  77402. var BABYLON;
  77403. (function (BABYLON) {
  77404. /**
  77405. * 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.
  77406. */
  77407. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  77408. __extends(ExtractHighlightsPostProcess, _super);
  77409. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77410. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77411. if (blockCompilation === void 0) { blockCompilation = false; }
  77412. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77413. /**
  77414. * The luminance threshold, pixels below this value will be set to black.
  77415. */
  77416. _this.threshold = 0.9;
  77417. /**
  77418. * Internal
  77419. */
  77420. _this._exposure = 1;
  77421. /**
  77422. * Post process which has the input texture to be used when performing highlight extraction
  77423. */
  77424. _this._inputPostProcess = null;
  77425. _this.onApplyObservable.add(function (effect) {
  77426. if (_this._inputPostProcess) {
  77427. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  77428. }
  77429. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  77430. effect.setFloat('exposure', _this._exposure);
  77431. });
  77432. return _this;
  77433. }
  77434. return ExtractHighlightsPostProcess;
  77435. }(BABYLON.PostProcess));
  77436. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  77437. })(BABYLON || (BABYLON = {}));
  77438. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  77439. var BABYLON;
  77440. (function (BABYLON) {
  77441. /**
  77442. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  77443. */
  77444. var BloomEffect = /** @class */ (function (_super) {
  77445. __extends(BloomEffect, _super);
  77446. /**
  77447. * Creates a new instance of @see BloomEffect
  77448. * @param scene The scene the effect belongs to.
  77449. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  77450. * @param bloomKernel The size of the kernel to be used when applying the blur.
  77451. * @param bloomWeight The the strength of bloom.
  77452. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77453. * @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)
  77454. */
  77455. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  77456. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77457. if (blockCompilation === void 0) { blockCompilation = false; }
  77458. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  77459. return _this._effects;
  77460. }, true) || this;
  77461. _this.bloomScale = bloomScale;
  77462. /**
  77463. * Internal
  77464. */
  77465. _this._effects = [];
  77466. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77467. _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);
  77468. _this._blurX.alwaysForcePOT = true;
  77469. _this._blurX.autoClear = false;
  77470. _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);
  77471. _this._blurY.alwaysForcePOT = true;
  77472. _this._blurY.autoClear = false;
  77473. _this.kernel = bloomKernel;
  77474. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  77475. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77476. _this._merge.autoClear = false;
  77477. _this._effects.push(_this._merge);
  77478. return _this;
  77479. }
  77480. Object.defineProperty(BloomEffect.prototype, "threshold", {
  77481. /**
  77482. * The luminance threshold to find bright areas of the image to bloom.
  77483. */
  77484. get: function () {
  77485. return this._downscale.threshold;
  77486. },
  77487. set: function (value) {
  77488. this._downscale.threshold = value;
  77489. },
  77490. enumerable: true,
  77491. configurable: true
  77492. });
  77493. Object.defineProperty(BloomEffect.prototype, "weight", {
  77494. /**
  77495. * The strength of the bloom.
  77496. */
  77497. get: function () {
  77498. return this._merge.weight;
  77499. },
  77500. set: function (value) {
  77501. this._merge.weight = value;
  77502. },
  77503. enumerable: true,
  77504. configurable: true
  77505. });
  77506. Object.defineProperty(BloomEffect.prototype, "kernel", {
  77507. /**
  77508. * Specifies the size of the bloom blur kernel, relative to the final output size
  77509. */
  77510. get: function () {
  77511. return this._blurX.kernel / this.bloomScale;
  77512. },
  77513. set: function (value) {
  77514. this._blurX.kernel = value * this.bloomScale;
  77515. this._blurY.kernel = value * this.bloomScale;
  77516. },
  77517. enumerable: true,
  77518. configurable: true
  77519. });
  77520. /**
  77521. * Disposes each of the internal effects for a given camera.
  77522. * @param camera The camera to dispose the effect on.
  77523. */
  77524. BloomEffect.prototype.disposeEffects = function (camera) {
  77525. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77526. this._effects[effectIndex].dispose(camera);
  77527. }
  77528. };
  77529. /**
  77530. * Internal
  77531. */
  77532. BloomEffect.prototype._updateEffects = function () {
  77533. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77534. this._effects[effectIndex].updateEffect();
  77535. }
  77536. };
  77537. /**
  77538. * Internal
  77539. * @returns if all the contained post processes are ready.
  77540. */
  77541. BloomEffect.prototype._isReady = function () {
  77542. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77543. if (!this._effects[effectIndex].isReady()) {
  77544. return false;
  77545. }
  77546. }
  77547. return true;
  77548. };
  77549. return BloomEffect;
  77550. }(BABYLON.PostProcessRenderEffect));
  77551. BABYLON.BloomEffect = BloomEffect;
  77552. })(BABYLON || (BABYLON = {}));
  77553. //# sourceMappingURL=babylon.bloomEffect.js.map
  77554. var BABYLON;
  77555. (function (BABYLON) {
  77556. /**
  77557. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  77558. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  77559. */
  77560. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  77561. __extends(DefaultRenderingPipeline, _super);
  77562. /**
  77563. * @constructor
  77564. * @param {string} name - The rendering pipeline name (default: "")
  77565. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  77566. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  77567. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  77568. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  77569. */
  77570. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  77571. if (name === void 0) { name = ""; }
  77572. if (hdr === void 0) { hdr = true; }
  77573. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77574. if (automaticBuild === void 0) { automaticBuild = true; }
  77575. var _this = _super.call(this, scene.getEngine(), name) || this;
  77576. _this._camerasToBeAttached = [];
  77577. /**
  77578. * ID of the sharpen post process,
  77579. */
  77580. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  77581. /**
  77582. * ID of the image processing post process;
  77583. */
  77584. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  77585. /**
  77586. * ID of the Fast Approximate Anti-Aliasing post process;
  77587. */
  77588. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  77589. /**
  77590. * ID of the chromatic aberration post process,
  77591. */
  77592. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  77593. /**
  77594. * ID of the grain post process
  77595. */
  77596. _this.GrainPostProcessId = "GrainPostProcessEffect";
  77597. /**
  77598. * Glow post process which adds a glow to emmisive areas of the image
  77599. */
  77600. _this._glowLayer = null;
  77601. /**
  77602. * Animations which can be used to tweak settings over a period of time
  77603. */
  77604. _this.animations = [];
  77605. _this._imageProcessingConfigurationObserver = null;
  77606. // Values
  77607. _this._sharpenEnabled = false;
  77608. _this._bloomEnabled = false;
  77609. _this._depthOfFieldEnabled = false;
  77610. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  77611. _this._fxaaEnabled = false;
  77612. _this._imageProcessingEnabled = true;
  77613. _this._bloomScale = 0.5;
  77614. _this._chromaticAberrationEnabled = false;
  77615. _this._grainEnabled = false;
  77616. _this._buildAllowed = true;
  77617. _this._resizeObserver = null;
  77618. _this._hardwareScaleLevel = 1.0;
  77619. _this._bloomKernel = 64;
  77620. /**
  77621. * Specifies the weight of the bloom in the final rendering
  77622. */
  77623. _this._bloomWeight = 0.15;
  77624. /**
  77625. * Specifies the luma threshold for the area that will be blurred by the bloom
  77626. */
  77627. _this._bloomThreshold = 0.9;
  77628. _this._samples = 1;
  77629. _this._hasCleared = false;
  77630. _this._prevPostProcess = null;
  77631. _this._prevPrevPostProcess = null;
  77632. _this._cameras = cameras || scene.cameras;
  77633. _this._camerasToBeAttached = _this._cameras.slice();
  77634. _this._buildAllowed = automaticBuild;
  77635. // Initialize
  77636. _this._scene = scene;
  77637. var caps = _this._scene.getEngine().getCaps();
  77638. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  77639. // Misc
  77640. if (_this._hdr) {
  77641. if (caps.textureHalfFloatRender) {
  77642. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77643. }
  77644. else if (caps.textureFloatRender) {
  77645. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77646. }
  77647. }
  77648. else {
  77649. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77650. }
  77651. // Attach
  77652. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77653. var engine = _this._scene.getEngine();
  77654. // Create post processes before hand so they can be modified before enabled.
  77655. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  77656. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77657. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  77658. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  77659. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  77660. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77661. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  77662. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77663. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  77664. _this._resizeObserver = engine.onResizeObservable.add(function () {
  77665. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  77666. _this.bloomKernel = _this.bloomKernel;
  77667. });
  77668. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  77669. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  77670. });
  77671. _this._buildPipeline();
  77672. return _this;
  77673. }
  77674. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  77675. get: function () {
  77676. return this._sharpenEnabled;
  77677. },
  77678. /**
  77679. * Enable or disable the sharpen process from the pipeline
  77680. */
  77681. set: function (enabled) {
  77682. if (this._sharpenEnabled === enabled) {
  77683. return;
  77684. }
  77685. this._sharpenEnabled = enabled;
  77686. this._buildPipeline();
  77687. },
  77688. enumerable: true,
  77689. configurable: true
  77690. });
  77691. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  77692. /**
  77693. * Specifies the size of the bloom blur kernel, relative to the final output size
  77694. */
  77695. get: function () {
  77696. return this._bloomKernel;
  77697. },
  77698. set: function (value) {
  77699. this._bloomKernel = value;
  77700. this.bloom.kernel = value / this._hardwareScaleLevel;
  77701. },
  77702. enumerable: true,
  77703. configurable: true
  77704. });
  77705. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  77706. get: function () {
  77707. return this._bloomWeight;
  77708. },
  77709. /**
  77710. * The strength of the bloom.
  77711. */
  77712. set: function (value) {
  77713. if (this._bloomWeight === value) {
  77714. return;
  77715. }
  77716. this.bloom.weight = value;
  77717. this._bloomWeight = value;
  77718. },
  77719. enumerable: true,
  77720. configurable: true
  77721. });
  77722. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  77723. get: function () {
  77724. return this._bloomThreshold;
  77725. },
  77726. /**
  77727. * The strength of the bloom.
  77728. */
  77729. set: function (value) {
  77730. if (this._bloomThreshold === value) {
  77731. return;
  77732. }
  77733. this.bloom.threshold = value;
  77734. this._bloomThreshold = value;
  77735. },
  77736. enumerable: true,
  77737. configurable: true
  77738. });
  77739. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  77740. get: function () {
  77741. return this._bloomScale;
  77742. },
  77743. /**
  77744. * The scale of the bloom, lower value will provide better performance.
  77745. */
  77746. set: function (value) {
  77747. if (this._bloomScale === value) {
  77748. return;
  77749. }
  77750. this._bloomScale = value;
  77751. // recreate bloom and dispose old as this setting is not dynamic
  77752. this._rebuildBloom();
  77753. this._buildPipeline();
  77754. },
  77755. enumerable: true,
  77756. configurable: true
  77757. });
  77758. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  77759. get: function () {
  77760. return this._bloomEnabled;
  77761. },
  77762. /**
  77763. * Enable or disable the bloom from the pipeline
  77764. */
  77765. set: function (enabled) {
  77766. if (this._bloomEnabled === enabled) {
  77767. return;
  77768. }
  77769. this._bloomEnabled = enabled;
  77770. this._buildPipeline();
  77771. },
  77772. enumerable: true,
  77773. configurable: true
  77774. });
  77775. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  77776. // recreate bloom and dispose old as this setting is not dynamic
  77777. var oldBloom = this.bloom;
  77778. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  77779. this.bloom.threshold = oldBloom.threshold;
  77780. for (var i = 0; i < this._cameras.length; i++) {
  77781. oldBloom.disposeEffects(this._cameras[i]);
  77782. }
  77783. };
  77784. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  77785. /**
  77786. * If the depth of field is enabled.
  77787. */
  77788. get: function () {
  77789. return this._depthOfFieldEnabled;
  77790. },
  77791. set: function (enabled) {
  77792. if (this._depthOfFieldEnabled === enabled) {
  77793. return;
  77794. }
  77795. this._depthOfFieldEnabled = enabled;
  77796. this._buildPipeline();
  77797. },
  77798. enumerable: true,
  77799. configurable: true
  77800. });
  77801. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  77802. /**
  77803. * Blur level of the depth of field effect. (Higher blur will effect performance)
  77804. */
  77805. get: function () {
  77806. return this._depthOfFieldBlurLevel;
  77807. },
  77808. set: function (value) {
  77809. if (this._depthOfFieldBlurLevel === value) {
  77810. return;
  77811. }
  77812. this._depthOfFieldBlurLevel = value;
  77813. // recreate dof and dispose old as this setting is not dynamic
  77814. var oldDof = this.depthOfField;
  77815. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  77816. this.depthOfField.focalLength = oldDof.focalLength;
  77817. this.depthOfField.focusDistance = oldDof.focusDistance;
  77818. this.depthOfField.fStop = oldDof.fStop;
  77819. this.depthOfField.lensSize = oldDof.lensSize;
  77820. for (var i = 0; i < this._cameras.length; i++) {
  77821. oldDof.disposeEffects(this._cameras[i]);
  77822. }
  77823. this._buildPipeline();
  77824. },
  77825. enumerable: true,
  77826. configurable: true
  77827. });
  77828. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  77829. get: function () {
  77830. return this._fxaaEnabled;
  77831. },
  77832. /**
  77833. * If the anti aliasing is enabled.
  77834. */
  77835. set: function (enabled) {
  77836. if (this._fxaaEnabled === enabled) {
  77837. return;
  77838. }
  77839. this._fxaaEnabled = enabled;
  77840. this._buildPipeline();
  77841. },
  77842. enumerable: true,
  77843. configurable: true
  77844. });
  77845. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  77846. get: function () {
  77847. return this._samples;
  77848. },
  77849. /**
  77850. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  77851. */
  77852. set: function (sampleCount) {
  77853. if (this._samples === sampleCount) {
  77854. return;
  77855. }
  77856. this._samples = sampleCount;
  77857. this._buildPipeline();
  77858. },
  77859. enumerable: true,
  77860. configurable: true
  77861. });
  77862. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  77863. get: function () {
  77864. return this._imageProcessingEnabled;
  77865. },
  77866. /**
  77867. * If image processing is enabled.
  77868. */
  77869. set: function (enabled) {
  77870. if (this._imageProcessingEnabled === enabled) {
  77871. return;
  77872. }
  77873. this._imageProcessingEnabled = enabled;
  77874. this._buildPipeline();
  77875. },
  77876. enumerable: true,
  77877. configurable: true
  77878. });
  77879. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  77880. get: function () {
  77881. return this._glowLayer == null;
  77882. },
  77883. /**
  77884. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  77885. */
  77886. set: function (enabled) {
  77887. if (enabled && !this._glowLayer) {
  77888. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  77889. }
  77890. else if (!enabled && this._glowLayer) {
  77891. this._glowLayer.dispose();
  77892. this._glowLayer = null;
  77893. }
  77894. },
  77895. enumerable: true,
  77896. configurable: true
  77897. });
  77898. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  77899. get: function () {
  77900. return this._chromaticAberrationEnabled;
  77901. },
  77902. /**
  77903. * Enable or disable the chromaticAberration process from the pipeline
  77904. */
  77905. set: function (enabled) {
  77906. if (this._chromaticAberrationEnabled === enabled) {
  77907. return;
  77908. }
  77909. this._chromaticAberrationEnabled = enabled;
  77910. this._buildPipeline();
  77911. },
  77912. enumerable: true,
  77913. configurable: true
  77914. });
  77915. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  77916. get: function () {
  77917. return this._grainEnabled;
  77918. },
  77919. /**
  77920. * Enable or disable the grain process from the pipeline
  77921. */
  77922. set: function (enabled) {
  77923. if (this._grainEnabled === enabled) {
  77924. return;
  77925. }
  77926. this._grainEnabled = enabled;
  77927. this._buildPipeline();
  77928. },
  77929. enumerable: true,
  77930. configurable: true
  77931. });
  77932. /**
  77933. * Force the compilation of the entire pipeline.
  77934. */
  77935. DefaultRenderingPipeline.prototype.prepare = function () {
  77936. var previousState = this._buildAllowed;
  77937. this._buildAllowed = true;
  77938. this._buildPipeline();
  77939. this._buildAllowed = previousState;
  77940. };
  77941. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  77942. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  77943. if (this._hasCleared) {
  77944. postProcess.autoClear = false;
  77945. }
  77946. else {
  77947. postProcess.autoClear = true;
  77948. this._scene.autoClear = false;
  77949. this._hasCleared = true;
  77950. }
  77951. if (!skipTextureSharing) {
  77952. if (this._prevPrevPostProcess) {
  77953. postProcess.shareOutputWith(this._prevPrevPostProcess);
  77954. }
  77955. else {
  77956. postProcess.useOwnOutput();
  77957. }
  77958. if (this._prevPostProcess) {
  77959. this._prevPrevPostProcess = this._prevPostProcess;
  77960. }
  77961. this._prevPostProcess = postProcess;
  77962. }
  77963. };
  77964. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  77965. var _this = this;
  77966. if (!this._buildAllowed) {
  77967. return;
  77968. }
  77969. this._scene.autoClear = true;
  77970. var engine = this._scene.getEngine();
  77971. this._disposePostProcesses();
  77972. if (this._cameras !== null) {
  77973. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77974. // get back cameras to be used to reattach pipeline
  77975. this._cameras = this._camerasToBeAttached.slice();
  77976. }
  77977. this._reset();
  77978. this._prevPostProcess = null;
  77979. this._prevPrevPostProcess = null;
  77980. this._hasCleared = false;
  77981. if (this.depthOfFieldEnabled) {
  77982. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  77983. this.depthOfField.depthTexture = depthTexture;
  77984. if (!this.depthOfField._isReady()) {
  77985. this.depthOfField._updateEffects();
  77986. }
  77987. this.addEffect(this.depthOfField);
  77988. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  77989. }
  77990. if (this.bloomEnabled) {
  77991. if (!this.bloom._isReady()) {
  77992. this.bloom._updateEffects();
  77993. }
  77994. this.addEffect(this.bloom);
  77995. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  77996. }
  77997. if (this._imageProcessingEnabled) {
  77998. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  77999. if (this._hdr) {
  78000. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  78001. this._setAutoClearAndTextureSharing(this.imageProcessing);
  78002. }
  78003. else {
  78004. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  78005. }
  78006. }
  78007. if (this.sharpenEnabled) {
  78008. if (!this.sharpen.isReady()) {
  78009. this.sharpen.updateEffect();
  78010. }
  78011. this.addEffect(this._sharpenEffect);
  78012. this._setAutoClearAndTextureSharing(this.sharpen);
  78013. }
  78014. if (this.grainEnabled) {
  78015. if (!this.grain.isReady()) {
  78016. this.grain.updateEffect();
  78017. }
  78018. this.addEffect(this._grainEffect);
  78019. this._setAutoClearAndTextureSharing(this.grain);
  78020. }
  78021. if (this.chromaticAberrationEnabled) {
  78022. if (!this.chromaticAberration.isReady()) {
  78023. this.chromaticAberration.updateEffect();
  78024. }
  78025. this.addEffect(this._chromaticAberrationEffect);
  78026. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  78027. }
  78028. if (this.fxaaEnabled) {
  78029. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78030. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  78031. this._setAutoClearAndTextureSharing(this.fxaa, true);
  78032. }
  78033. if (this._cameras !== null) {
  78034. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78035. }
  78036. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  78037. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  78038. }
  78039. };
  78040. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  78041. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  78042. for (var i = 0; i < this._cameras.length; i++) {
  78043. var camera = this._cameras[i];
  78044. if (this.imageProcessing) {
  78045. this.imageProcessing.dispose(camera);
  78046. }
  78047. if (this.fxaa) {
  78048. this.fxaa.dispose(camera);
  78049. }
  78050. // These are created in the constructor and should not be disposed on every pipeline change
  78051. if (disposeNonRecreated) {
  78052. if (this.sharpen) {
  78053. this.sharpen.dispose(camera);
  78054. }
  78055. if (this.depthOfField) {
  78056. this.depthOfField.disposeEffects(camera);
  78057. }
  78058. if (this.bloom) {
  78059. this.bloom.disposeEffects(camera);
  78060. }
  78061. if (this.chromaticAberration) {
  78062. this.chromaticAberration.dispose(camera);
  78063. }
  78064. if (this.grain) {
  78065. this.grain.dispose(camera);
  78066. }
  78067. if (this._glowLayer) {
  78068. this._glowLayer.dispose();
  78069. }
  78070. }
  78071. }
  78072. this.imageProcessing = null;
  78073. this.fxaa = null;
  78074. if (disposeNonRecreated) {
  78075. this.sharpen = null;
  78076. this._sharpenEffect = null;
  78077. this.depthOfField = null;
  78078. this.bloom = null;
  78079. this.chromaticAberration = null;
  78080. this._chromaticAberrationEffect = null;
  78081. this.grain = null;
  78082. this._grainEffect = null;
  78083. this._glowLayer = null;
  78084. }
  78085. };
  78086. /**
  78087. * Adds a camera to the pipeline
  78088. * @param camera the camera to be added
  78089. */
  78090. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  78091. this._camerasToBeAttached.push(camera);
  78092. this._buildPipeline();
  78093. };
  78094. /**
  78095. * Removes a camera from the pipeline
  78096. * @param camera the camera to remove
  78097. */
  78098. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  78099. var index = this._camerasToBeAttached.indexOf(camera);
  78100. this._camerasToBeAttached.splice(index, 1);
  78101. this._buildPipeline();
  78102. };
  78103. /**
  78104. * Dispose of the pipeline and stop all post processes
  78105. */
  78106. DefaultRenderingPipeline.prototype.dispose = function () {
  78107. this._disposePostProcesses(true);
  78108. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78109. this._scene.autoClear = true;
  78110. if (this._resizeObserver) {
  78111. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  78112. this._resizeObserver = null;
  78113. }
  78114. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  78115. _super.prototype.dispose.call(this);
  78116. };
  78117. /**
  78118. * Serialize the rendering pipeline (Used when exporting)
  78119. * @returns the serialized object
  78120. */
  78121. DefaultRenderingPipeline.prototype.serialize = function () {
  78122. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78123. serializationObject.customType = "DefaultRenderingPipeline";
  78124. return serializationObject;
  78125. };
  78126. /**
  78127. * Parse the serialized pipeline
  78128. * @param source Source pipeline.
  78129. * @param scene The scene to load the pipeline to.
  78130. * @param rootUrl The URL of the serialized pipeline.
  78131. * @returns An instantiated pipeline from the serialized object.
  78132. */
  78133. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78134. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  78135. };
  78136. __decorate([
  78137. BABYLON.serialize()
  78138. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  78139. __decorate([
  78140. BABYLON.serialize()
  78141. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  78142. __decorate([
  78143. BABYLON.serialize()
  78144. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  78145. __decorate([
  78146. BABYLON.serialize()
  78147. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  78148. __decorate([
  78149. BABYLON.serialize()
  78150. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  78151. __decorate([
  78152. BABYLON.serialize()
  78153. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  78154. __decorate([
  78155. BABYLON.serialize()
  78156. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  78157. __decorate([
  78158. BABYLON.serialize()
  78159. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  78160. __decorate([
  78161. BABYLON.serialize()
  78162. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  78163. __decorate([
  78164. BABYLON.serialize()
  78165. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  78166. __decorate([
  78167. BABYLON.serialize()
  78168. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  78169. __decorate([
  78170. BABYLON.serialize()
  78171. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  78172. __decorate([
  78173. BABYLON.serialize()
  78174. ], DefaultRenderingPipeline.prototype, "samples", null);
  78175. __decorate([
  78176. BABYLON.serialize()
  78177. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  78178. __decorate([
  78179. BABYLON.serialize()
  78180. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  78181. __decorate([
  78182. BABYLON.serialize()
  78183. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  78184. __decorate([
  78185. BABYLON.serialize()
  78186. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  78187. return DefaultRenderingPipeline;
  78188. }(BABYLON.PostProcessRenderPipeline));
  78189. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  78190. })(BABYLON || (BABYLON = {}));
  78191. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  78192. var BABYLON;
  78193. (function (BABYLON) {
  78194. /**
  78195. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78196. */
  78197. var GeometryBufferRenderer = /** @class */ (function () {
  78198. /**
  78199. * Creates a new G Buffer for the scene
  78200. * @param scene The scene the buffer belongs to
  78201. * @param ratio How big is the buffer related to the main canvas.
  78202. */
  78203. function GeometryBufferRenderer(scene, ratio) {
  78204. if (ratio === void 0) { ratio = 1; }
  78205. this._enablePosition = false;
  78206. this._scene = scene;
  78207. this._ratio = ratio;
  78208. // Render target
  78209. this._createRenderTargets();
  78210. }
  78211. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78212. /**
  78213. * Set the render list (meshes to be rendered) used in the G buffer.
  78214. */
  78215. set: function (meshes) {
  78216. this._multiRenderTarget.renderList = meshes;
  78217. },
  78218. enumerable: true,
  78219. configurable: true
  78220. });
  78221. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78222. /**
  78223. * Gets wether or not G buffer are supported by the running hardware.
  78224. * This requires draw buffer supports
  78225. */
  78226. get: function () {
  78227. return this._multiRenderTarget.isSupported;
  78228. },
  78229. enumerable: true,
  78230. configurable: true
  78231. });
  78232. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78233. /**
  78234. * Gets wether or not position are enabled for the G buffer.
  78235. */
  78236. get: function () {
  78237. return this._enablePosition;
  78238. },
  78239. /**
  78240. * Sets wether or not position are enabled for the G buffer.
  78241. */
  78242. set: function (enable) {
  78243. this._enablePosition = enable;
  78244. this.dispose();
  78245. this._createRenderTargets();
  78246. },
  78247. enumerable: true,
  78248. configurable: true
  78249. });
  78250. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78251. /**
  78252. * Gets the scene associated with the buffer.
  78253. */
  78254. get: function () {
  78255. return this._scene;
  78256. },
  78257. enumerable: true,
  78258. configurable: true
  78259. });
  78260. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78261. /**
  78262. * Gets the ratio used by the buffer during its creation.
  78263. * How big is the buffer related to the main canvas.
  78264. */
  78265. get: function () {
  78266. return this._ratio;
  78267. },
  78268. enumerable: true,
  78269. configurable: true
  78270. });
  78271. /**
  78272. * Checks wether everything is ready to render a submesh to the G buffer.
  78273. * @param subMesh the submesh to check readiness for
  78274. * @param useInstances is the mesh drawn using instance or not
  78275. * @returns true if ready otherwise false
  78276. */
  78277. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78278. var material = subMesh.getMaterial();
  78279. if (material && material.disableDepthWrite) {
  78280. return false;
  78281. }
  78282. var defines = [];
  78283. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78284. var mesh = subMesh.getMesh();
  78285. // Alpha test
  78286. if (material && material.needAlphaTesting()) {
  78287. defines.push("#define ALPHATEST");
  78288. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78289. attribs.push(BABYLON.VertexBuffer.UVKind);
  78290. defines.push("#define UV1");
  78291. }
  78292. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78293. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78294. defines.push("#define UV2");
  78295. }
  78296. }
  78297. // Buffers
  78298. if (this._enablePosition) {
  78299. defines.push("#define POSITION");
  78300. }
  78301. // Bones
  78302. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78303. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78304. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78305. if (mesh.numBoneInfluencers > 4) {
  78306. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78307. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78308. }
  78309. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78310. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78311. }
  78312. else {
  78313. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78314. }
  78315. // Instances
  78316. if (useInstances) {
  78317. defines.push("#define INSTANCES");
  78318. attribs.push("world0");
  78319. attribs.push("world1");
  78320. attribs.push("world2");
  78321. attribs.push("world3");
  78322. }
  78323. // Get correct effect
  78324. var join = defines.join("\n");
  78325. if (this._cachedDefines !== join) {
  78326. this._cachedDefines = join;
  78327. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78328. }
  78329. return this._effect.isReady();
  78330. };
  78331. /**
  78332. * Gets the current underlying G Buffer.
  78333. * @returns the buffer
  78334. */
  78335. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78336. return this._multiRenderTarget;
  78337. };
  78338. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78339. /**
  78340. * Gets the number of samples used to render the buffer (anti aliasing).
  78341. */
  78342. get: function () {
  78343. return this._multiRenderTarget.samples;
  78344. },
  78345. /**
  78346. * Sets the number of samples used to render the buffer (anti aliasing).
  78347. */
  78348. set: function (value) {
  78349. this._multiRenderTarget.samples = value;
  78350. },
  78351. enumerable: true,
  78352. configurable: true
  78353. });
  78354. /**
  78355. * Disposes the renderer and frees up associated resources.
  78356. */
  78357. GeometryBufferRenderer.prototype.dispose = function () {
  78358. this.getGBuffer().dispose();
  78359. };
  78360. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78361. var _this = this;
  78362. var engine = this._scene.getEngine();
  78363. var count = this._enablePosition ? 3 : 2;
  78364. 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 });
  78365. if (!this.isSupported) {
  78366. return;
  78367. }
  78368. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78369. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78370. this._multiRenderTarget.refreshRate = 1;
  78371. this._multiRenderTarget.renderParticles = false;
  78372. this._multiRenderTarget.renderList = null;
  78373. // set default depth value to 1.0 (far away)
  78374. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78375. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78376. });
  78377. // Custom render function
  78378. var renderSubMesh = function (subMesh) {
  78379. var mesh = subMesh.getRenderingMesh();
  78380. var scene = _this._scene;
  78381. var engine = scene.getEngine();
  78382. var material = subMesh.getMaterial();
  78383. if (!material) {
  78384. return;
  78385. }
  78386. // Culling
  78387. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78388. // Managing instances
  78389. var batch = mesh._getInstancesRenderList(subMesh._id);
  78390. if (batch.mustReturn) {
  78391. return;
  78392. }
  78393. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78394. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78395. engine.enableEffect(_this._effect);
  78396. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78397. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78398. _this._effect.setMatrix("view", scene.getViewMatrix());
  78399. // Alpha test
  78400. if (material && material.needAlphaTesting()) {
  78401. var alphaTexture = material.getAlphaTestTexture();
  78402. if (alphaTexture) {
  78403. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78404. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78405. }
  78406. }
  78407. // Bones
  78408. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78409. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78410. }
  78411. // Draw
  78412. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78413. }
  78414. };
  78415. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78416. var index;
  78417. if (depthOnlySubMeshes.length) {
  78418. engine.setColorWrite(false);
  78419. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78420. renderSubMesh(depthOnlySubMeshes.data[index]);
  78421. }
  78422. engine.setColorWrite(true);
  78423. }
  78424. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78425. renderSubMesh(opaqueSubMeshes.data[index]);
  78426. }
  78427. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78428. renderSubMesh(alphaTestSubMeshes.data[index]);
  78429. }
  78430. };
  78431. };
  78432. return GeometryBufferRenderer;
  78433. }());
  78434. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78435. })(BABYLON || (BABYLON = {}));
  78436. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78437. var BABYLON;
  78438. (function (BABYLON) {
  78439. /**
  78440. * This groups together the common properties used for image processing either in direct forward pass
  78441. * or through post processing effect depending on the use of the image processing pipeline in your scene
  78442. * or not.
  78443. */
  78444. var ImageProcessingConfiguration = /** @class */ (function () {
  78445. function ImageProcessingConfiguration() {
  78446. /**
  78447. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  78448. */
  78449. this.colorCurves = new BABYLON.ColorCurves();
  78450. this._colorCurvesEnabled = false;
  78451. this._colorGradingEnabled = false;
  78452. this._colorGradingWithGreenDepth = true;
  78453. this._colorGradingBGR = true;
  78454. this._exposure = 1.0;
  78455. this._toneMappingEnabled = false;
  78456. this._contrast = 1.0;
  78457. /**
  78458. * Vignette stretch size.
  78459. */
  78460. this.vignetteStretch = 0;
  78461. /**
  78462. * Vignette centre X Offset.
  78463. */
  78464. this.vignetteCentreX = 0;
  78465. /**
  78466. * Vignette centre Y Offset.
  78467. */
  78468. this.vignetteCentreY = 0;
  78469. /**
  78470. * Vignette weight or intensity of the vignette effect.
  78471. */
  78472. this.vignetteWeight = 1.5;
  78473. /**
  78474. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78475. * if vignetteEnabled is set to true.
  78476. */
  78477. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78478. /**
  78479. * Camera field of view used by the Vignette effect.
  78480. */
  78481. this.vignetteCameraFov = 0.5;
  78482. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  78483. this._vignetteEnabled = false;
  78484. this._applyByPostProcess = false;
  78485. this._isEnabled = true;
  78486. /**
  78487. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  78488. */
  78489. this.onUpdateParameters = new BABYLON.Observable();
  78490. }
  78491. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  78492. /**
  78493. * Gets wether the color curves effect is enabled.
  78494. */
  78495. get: function () {
  78496. return this._colorCurvesEnabled;
  78497. },
  78498. /**
  78499. * Sets wether the color curves effect is enabled.
  78500. */
  78501. set: function (value) {
  78502. if (this._colorCurvesEnabled === value) {
  78503. return;
  78504. }
  78505. this._colorCurvesEnabled = value;
  78506. this._updateParameters();
  78507. },
  78508. enumerable: true,
  78509. configurable: true
  78510. });
  78511. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  78512. /**
  78513. * Gets wether the color grading effect is enabled.
  78514. */
  78515. get: function () {
  78516. return this._colorGradingEnabled;
  78517. },
  78518. /**
  78519. * Sets wether the color grading effect is enabled.
  78520. */
  78521. set: function (value) {
  78522. if (this._colorGradingEnabled === value) {
  78523. return;
  78524. }
  78525. this._colorGradingEnabled = value;
  78526. this._updateParameters();
  78527. },
  78528. enumerable: true,
  78529. configurable: true
  78530. });
  78531. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  78532. /**
  78533. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  78534. */
  78535. get: function () {
  78536. return this._colorGradingWithGreenDepth;
  78537. },
  78538. /**
  78539. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  78540. */
  78541. set: function (value) {
  78542. if (this._colorGradingWithGreenDepth === value) {
  78543. return;
  78544. }
  78545. this._colorGradingWithGreenDepth = value;
  78546. this._updateParameters();
  78547. },
  78548. enumerable: true,
  78549. configurable: true
  78550. });
  78551. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  78552. /**
  78553. * Gets wether the color grading texture contains BGR values.
  78554. */
  78555. get: function () {
  78556. return this._colorGradingBGR;
  78557. },
  78558. /**
  78559. * Sets wether the color grading texture contains BGR values.
  78560. */
  78561. set: function (value) {
  78562. if (this._colorGradingBGR === value) {
  78563. return;
  78564. }
  78565. this._colorGradingBGR = value;
  78566. this._updateParameters();
  78567. },
  78568. enumerable: true,
  78569. configurable: true
  78570. });
  78571. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  78572. /**
  78573. * Gets the Exposure used in the effect.
  78574. */
  78575. get: function () {
  78576. return this._exposure;
  78577. },
  78578. /**
  78579. * Sets the Exposure used in the effect.
  78580. */
  78581. set: function (value) {
  78582. if (this._exposure === value) {
  78583. return;
  78584. }
  78585. this._exposure = value;
  78586. this._updateParameters();
  78587. },
  78588. enumerable: true,
  78589. configurable: true
  78590. });
  78591. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  78592. /**
  78593. * Gets wether the tone mapping effect is enabled.
  78594. */
  78595. get: function () {
  78596. return this._toneMappingEnabled;
  78597. },
  78598. /**
  78599. * Sets wether the tone mapping effect is enabled.
  78600. */
  78601. set: function (value) {
  78602. if (this._toneMappingEnabled === value) {
  78603. return;
  78604. }
  78605. this._toneMappingEnabled = value;
  78606. this._updateParameters();
  78607. },
  78608. enumerable: true,
  78609. configurable: true
  78610. });
  78611. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  78612. /**
  78613. * Gets the contrast used in the effect.
  78614. */
  78615. get: function () {
  78616. return this._contrast;
  78617. },
  78618. /**
  78619. * Sets the contrast used in the effect.
  78620. */
  78621. set: function (value) {
  78622. if (this._contrast === value) {
  78623. return;
  78624. }
  78625. this._contrast = value;
  78626. this._updateParameters();
  78627. },
  78628. enumerable: true,
  78629. configurable: true
  78630. });
  78631. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  78632. /**
  78633. * Gets the vignette blend mode allowing different kind of effect.
  78634. */
  78635. get: function () {
  78636. return this._vignetteBlendMode;
  78637. },
  78638. /**
  78639. * Sets the vignette blend mode allowing different kind of effect.
  78640. */
  78641. set: function (value) {
  78642. if (this._vignetteBlendMode === value) {
  78643. return;
  78644. }
  78645. this._vignetteBlendMode = value;
  78646. this._updateParameters();
  78647. },
  78648. enumerable: true,
  78649. configurable: true
  78650. });
  78651. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  78652. /**
  78653. * Gets wether the vignette effect is enabled.
  78654. */
  78655. get: function () {
  78656. return this._vignetteEnabled;
  78657. },
  78658. /**
  78659. * Sets wether the vignette effect is enabled.
  78660. */
  78661. set: function (value) {
  78662. if (this._vignetteEnabled === value) {
  78663. return;
  78664. }
  78665. this._vignetteEnabled = value;
  78666. this._updateParameters();
  78667. },
  78668. enumerable: true,
  78669. configurable: true
  78670. });
  78671. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  78672. /**
  78673. * Gets wether the image processing is applied through a post process or not.
  78674. */
  78675. get: function () {
  78676. return this._applyByPostProcess;
  78677. },
  78678. /**
  78679. * Sets wether the image processing is applied through a post process or not.
  78680. */
  78681. set: function (value) {
  78682. if (this._applyByPostProcess === value) {
  78683. return;
  78684. }
  78685. this._applyByPostProcess = value;
  78686. this._updateParameters();
  78687. },
  78688. enumerable: true,
  78689. configurable: true
  78690. });
  78691. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  78692. /**
  78693. * Gets wether the image processing is enabled or not.
  78694. */
  78695. get: function () {
  78696. return this._isEnabled;
  78697. },
  78698. /**
  78699. * Sets wether the image processing is enabled or not.
  78700. */
  78701. set: function (value) {
  78702. if (this._isEnabled === value) {
  78703. return;
  78704. }
  78705. this._isEnabled = value;
  78706. this._updateParameters();
  78707. },
  78708. enumerable: true,
  78709. configurable: true
  78710. });
  78711. /**
  78712. * Method called each time the image processing information changes requires to recompile the effect.
  78713. */
  78714. ImageProcessingConfiguration.prototype._updateParameters = function () {
  78715. this.onUpdateParameters.notifyObservers(this);
  78716. };
  78717. ImageProcessingConfiguration.prototype.getClassName = function () {
  78718. return "ImageProcessingConfiguration";
  78719. };
  78720. /**
  78721. * Prepare the list of uniforms associated with the Image Processing effects.
  78722. * @param uniformsList The list of uniforms used in the effect
  78723. * @param defines the list of defines currently in use
  78724. */
  78725. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  78726. if (defines.EXPOSURE) {
  78727. uniforms.push("exposureLinear");
  78728. }
  78729. if (defines.CONTRAST) {
  78730. uniforms.push("contrast");
  78731. }
  78732. if (defines.COLORGRADING) {
  78733. uniforms.push("colorTransformSettings");
  78734. }
  78735. if (defines.VIGNETTE) {
  78736. uniforms.push("vInverseScreenSize");
  78737. uniforms.push("vignetteSettings1");
  78738. uniforms.push("vignetteSettings2");
  78739. }
  78740. if (defines.COLORCURVES) {
  78741. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  78742. }
  78743. };
  78744. /**
  78745. * Prepare the list of samplers associated with the Image Processing effects.
  78746. * @param uniformsList The list of uniforms used in the effect
  78747. * @param defines the list of defines currently in use
  78748. */
  78749. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  78750. if (defines.COLORGRADING) {
  78751. samplersList.push("txColorTransform");
  78752. }
  78753. };
  78754. /**
  78755. * Prepare the list of defines associated to the shader.
  78756. * @param defines the list of defines to complete
  78757. */
  78758. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  78759. if (forPostProcess === void 0) { forPostProcess = false; }
  78760. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  78761. defines.VIGNETTE = false;
  78762. defines.TONEMAPPING = false;
  78763. defines.CONTRAST = false;
  78764. defines.EXPOSURE = false;
  78765. defines.COLORCURVES = false;
  78766. defines.COLORGRADING = false;
  78767. defines.COLORGRADING3D = false;
  78768. defines.IMAGEPROCESSING = false;
  78769. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  78770. return;
  78771. }
  78772. defines.VIGNETTE = this.vignetteEnabled;
  78773. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  78774. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  78775. defines.TONEMAPPING = this.toneMappingEnabled;
  78776. defines.CONTRAST = (this.contrast !== 1.0);
  78777. defines.EXPOSURE = (this.exposure !== 1.0);
  78778. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  78779. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  78780. if (defines.COLORGRADING) {
  78781. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  78782. }
  78783. else {
  78784. defines.COLORGRADING3D = false;
  78785. }
  78786. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  78787. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  78788. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  78789. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  78790. };
  78791. /**
  78792. * Returns true if all the image processing information are ready.
  78793. */
  78794. ImageProcessingConfiguration.prototype.isReady = function () {
  78795. // Color Grading texure can not be none blocking.
  78796. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  78797. };
  78798. /**
  78799. * Binds the image processing to the shader.
  78800. * @param effect The effect to bind to
  78801. */
  78802. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  78803. if (aspectRatio === void 0) { aspectRatio = 1; }
  78804. // Color Curves
  78805. if (this._colorCurvesEnabled && this.colorCurves) {
  78806. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  78807. }
  78808. // Vignette
  78809. if (this._vignetteEnabled) {
  78810. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  78811. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  78812. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  78813. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  78814. var vignetteScaleX = vignetteScaleY * aspectRatio;
  78815. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  78816. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  78817. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  78818. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  78819. var vignettePower = -2.0 * this.vignetteWeight;
  78820. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  78821. }
  78822. // Exposure
  78823. effect.setFloat("exposureLinear", this.exposure);
  78824. // Contrast
  78825. effect.setFloat("contrast", this.contrast);
  78826. // Color transform settings
  78827. if (this.colorGradingTexture) {
  78828. effect.setTexture("txColorTransform", this.colorGradingTexture);
  78829. var textureSize = this.colorGradingTexture.getSize().height;
  78830. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  78831. 0.5 / textureSize, // textureOffset
  78832. textureSize, // textureSize
  78833. this.colorGradingTexture.level // weight
  78834. );
  78835. }
  78836. };
  78837. /**
  78838. * Clones the current image processing instance.
  78839. * @return The cloned image processing
  78840. */
  78841. ImageProcessingConfiguration.prototype.clone = function () {
  78842. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  78843. };
  78844. /**
  78845. * Serializes the current image processing instance to a json representation.
  78846. * @return a JSON representation
  78847. */
  78848. ImageProcessingConfiguration.prototype.serialize = function () {
  78849. return BABYLON.SerializationHelper.Serialize(this);
  78850. };
  78851. /**
  78852. * Parses the image processing from a json representation.
  78853. * @param source the JSON source to parse
  78854. * @return The parsed image processing
  78855. */
  78856. ImageProcessingConfiguration.Parse = function (source) {
  78857. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  78858. };
  78859. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  78860. /**
  78861. * Used to apply the vignette as a mix with the pixel color.
  78862. */
  78863. get: function () {
  78864. return this._VIGNETTEMODE_MULTIPLY;
  78865. },
  78866. enumerable: true,
  78867. configurable: true
  78868. });
  78869. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  78870. /**
  78871. * Used to apply the vignette as a replacement of the pixel color.
  78872. */
  78873. get: function () {
  78874. return this._VIGNETTEMODE_OPAQUE;
  78875. },
  78876. enumerable: true,
  78877. configurable: true
  78878. });
  78879. // Static constants associated to the image processing.
  78880. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  78881. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  78882. __decorate([
  78883. BABYLON.serializeAsColorCurves()
  78884. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  78885. __decorate([
  78886. BABYLON.serialize()
  78887. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  78888. __decorate([
  78889. BABYLON.serializeAsTexture()
  78890. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  78891. __decorate([
  78892. BABYLON.serialize()
  78893. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  78894. __decorate([
  78895. BABYLON.serialize()
  78896. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  78897. __decorate([
  78898. BABYLON.serialize()
  78899. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  78900. __decorate([
  78901. BABYLON.serialize()
  78902. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  78903. __decorate([
  78904. BABYLON.serialize()
  78905. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  78906. __decorate([
  78907. BABYLON.serialize()
  78908. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  78909. __decorate([
  78910. BABYLON.serialize()
  78911. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  78912. __decorate([
  78913. BABYLON.serialize()
  78914. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  78915. __decorate([
  78916. BABYLON.serialize()
  78917. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  78918. __decorate([
  78919. BABYLON.serialize()
  78920. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  78921. __decorate([
  78922. BABYLON.serializeAsColor4()
  78923. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  78924. __decorate([
  78925. BABYLON.serialize()
  78926. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  78927. __decorate([
  78928. BABYLON.serialize()
  78929. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  78930. __decorate([
  78931. BABYLON.serialize()
  78932. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  78933. __decorate([
  78934. BABYLON.serialize()
  78935. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  78936. __decorate([
  78937. BABYLON.serialize()
  78938. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  78939. return ImageProcessingConfiguration;
  78940. }());
  78941. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  78942. })(BABYLON || (BABYLON = {}));
  78943. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  78944. var BABYLON;
  78945. (function (BABYLON) {
  78946. /**
  78947. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  78948. * It can help converting any input color in a desired output one. This can then be used to create effects
  78949. * from sepia, black and white to sixties or futuristic rendering...
  78950. *
  78951. * The only supported format is currently 3dl.
  78952. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  78953. */
  78954. var ColorGradingTexture = /** @class */ (function (_super) {
  78955. __extends(ColorGradingTexture, _super);
  78956. /**
  78957. * Instantiates a ColorGradingTexture from the following parameters.
  78958. *
  78959. * @param url The location of the color gradind data (currently only supporting 3dl)
  78960. * @param scene The scene the texture will be used in
  78961. */
  78962. function ColorGradingTexture(url, scene) {
  78963. var _this = _super.call(this, scene) || this;
  78964. if (!url) {
  78965. return _this;
  78966. }
  78967. _this._engine = scene.getEngine();
  78968. _this._textureMatrix = BABYLON.Matrix.Identity();
  78969. _this.name = url;
  78970. _this.url = url;
  78971. _this.hasAlpha = false;
  78972. _this.isCube = false;
  78973. _this.is3D = _this._engine.webGLVersion > 1;
  78974. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78975. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78976. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78977. _this.anisotropicFilteringLevel = 1;
  78978. _this._texture = _this._getFromCache(url, true);
  78979. if (!_this._texture) {
  78980. if (!scene.useDelayedTextureLoading) {
  78981. _this.loadTexture();
  78982. }
  78983. else {
  78984. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78985. }
  78986. }
  78987. return _this;
  78988. }
  78989. /**
  78990. * Returns the texture matrix used in most of the material.
  78991. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  78992. */
  78993. ColorGradingTexture.prototype.getTextureMatrix = function () {
  78994. return this._textureMatrix;
  78995. };
  78996. /**
  78997. * Occurs when the file being loaded is a .3dl LUT file.
  78998. */
  78999. ColorGradingTexture.prototype.load3dlTexture = function () {
  79000. var engine = this._engine;
  79001. var texture;
  79002. if (engine.webGLVersion === 1) {
  79003. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79004. }
  79005. else {
  79006. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79007. }
  79008. this._texture = texture;
  79009. var callback = function (text) {
  79010. if (typeof text !== "string") {
  79011. return;
  79012. }
  79013. var data = null;
  79014. var tempData = null;
  79015. var line;
  79016. var lines = text.split('\n');
  79017. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  79018. var maxColor = 0;
  79019. for (var i = 0; i < lines.length; i++) {
  79020. line = lines[i];
  79021. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  79022. continue;
  79023. if (line.indexOf('#') === 0)
  79024. continue;
  79025. var words = line.split(" ");
  79026. if (size === 0) {
  79027. // Number of space + one
  79028. size = words.length;
  79029. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  79030. tempData = new Float32Array(size * size * size * 4);
  79031. continue;
  79032. }
  79033. if (size != 0) {
  79034. var r = Math.max(parseInt(words[0]), 0);
  79035. var g = Math.max(parseInt(words[1]), 0);
  79036. var b = Math.max(parseInt(words[2]), 0);
  79037. maxColor = Math.max(r, maxColor);
  79038. maxColor = Math.max(g, maxColor);
  79039. maxColor = Math.max(b, maxColor);
  79040. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  79041. if (tempData) {
  79042. tempData[pixelStorageIndex + 0] = r;
  79043. tempData[pixelStorageIndex + 1] = g;
  79044. tempData[pixelStorageIndex + 2] = b;
  79045. }
  79046. pixelIndexSlice++;
  79047. if (pixelIndexSlice % size == 0) {
  79048. pixelIndexH++;
  79049. pixelIndexSlice = 0;
  79050. if (pixelIndexH % size == 0) {
  79051. pixelIndexW++;
  79052. pixelIndexH = 0;
  79053. }
  79054. }
  79055. }
  79056. }
  79057. if (tempData && data) {
  79058. for (var i = 0; i < tempData.length; i++) {
  79059. if (i > 0 && (i + 1) % 4 === 0) {
  79060. data[i] = 255;
  79061. }
  79062. else {
  79063. var value = tempData[i];
  79064. data[i] = (value / maxColor * 255);
  79065. }
  79066. }
  79067. }
  79068. if (texture.is3D) {
  79069. texture.updateSize(size, size, size);
  79070. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79071. }
  79072. else {
  79073. texture.updateSize(size * size, size);
  79074. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79075. }
  79076. };
  79077. var scene = this.getScene();
  79078. if (scene) {
  79079. scene._loadFile(this.url, callback);
  79080. }
  79081. else {
  79082. this._engine._loadFile(this.url, callback);
  79083. }
  79084. return this._texture;
  79085. };
  79086. /**
  79087. * Starts the loading process of the texture.
  79088. */
  79089. ColorGradingTexture.prototype.loadTexture = function () {
  79090. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  79091. this.load3dlTexture();
  79092. }
  79093. };
  79094. /**
  79095. * Clones the color gradind texture.
  79096. */
  79097. ColorGradingTexture.prototype.clone = function () {
  79098. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  79099. // Base texture
  79100. newTexture.level = this.level;
  79101. return newTexture;
  79102. };
  79103. /**
  79104. * Called during delayed load for textures.
  79105. */
  79106. ColorGradingTexture.prototype.delayLoad = function () {
  79107. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79108. return;
  79109. }
  79110. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79111. this._texture = this._getFromCache(this.url, true);
  79112. if (!this._texture) {
  79113. this.loadTexture();
  79114. }
  79115. };
  79116. /**
  79117. * Parses a color grading texture serialized by Babylon.
  79118. * @param parsedTexture The texture information being parsedTexture
  79119. * @param scene The scene to load the texture in
  79120. * @param rootUrl The root url of the data assets to load
  79121. * @return A color gradind texture
  79122. */
  79123. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79124. var texture = null;
  79125. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79126. texture = new ColorGradingTexture(parsedTexture.name, scene);
  79127. texture.name = parsedTexture.name;
  79128. texture.level = parsedTexture.level;
  79129. }
  79130. return texture;
  79131. };
  79132. /**
  79133. * Serializes the LUT texture to json format.
  79134. */
  79135. ColorGradingTexture.prototype.serialize = function () {
  79136. if (!this.name) {
  79137. return null;
  79138. }
  79139. var serializationObject = {};
  79140. serializationObject.name = this.name;
  79141. serializationObject.level = this.level;
  79142. serializationObject.customType = "BABYLON.ColorGradingTexture";
  79143. return serializationObject;
  79144. };
  79145. /**
  79146. * Empty line regex stored for GC.
  79147. */
  79148. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  79149. return ColorGradingTexture;
  79150. }(BABYLON.BaseTexture));
  79151. BABYLON.ColorGradingTexture = ColorGradingTexture;
  79152. })(BABYLON || (BABYLON = {}));
  79153. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  79154. var BABYLON;
  79155. (function (BABYLON) {
  79156. /**
  79157. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79158. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79159. * 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;
  79160. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79161. */
  79162. var ColorCurves = /** @class */ (function () {
  79163. function ColorCurves() {
  79164. this._dirty = true;
  79165. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  79166. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  79167. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79168. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  79169. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79170. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  79171. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  79172. this._globalHue = 30;
  79173. this._globalDensity = 0;
  79174. this._globalSaturation = 0;
  79175. this._globalExposure = 0;
  79176. this._highlightsHue = 30;
  79177. this._highlightsDensity = 0;
  79178. this._highlightsSaturation = 0;
  79179. this._highlightsExposure = 0;
  79180. this._midtonesHue = 30;
  79181. this._midtonesDensity = 0;
  79182. this._midtonesSaturation = 0;
  79183. this._midtonesExposure = 0;
  79184. this._shadowsHue = 30;
  79185. this._shadowsDensity = 0;
  79186. this._shadowsSaturation = 0;
  79187. this._shadowsExposure = 0;
  79188. }
  79189. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  79190. /**
  79191. * Gets the global Hue value.
  79192. * 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).
  79193. */
  79194. get: function () {
  79195. return this._globalHue;
  79196. },
  79197. /**
  79198. * Sets the global Hue value.
  79199. * 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).
  79200. */
  79201. set: function (value) {
  79202. this._globalHue = value;
  79203. this._dirty = true;
  79204. },
  79205. enumerable: true,
  79206. configurable: true
  79207. });
  79208. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  79209. /**
  79210. * Gets the global Density value.
  79211. * 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.
  79212. * Values less than zero provide a filter of opposite hue.
  79213. */
  79214. get: function () {
  79215. return this._globalDensity;
  79216. },
  79217. /**
  79218. * Sets the global Density value.
  79219. * 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.
  79220. * Values less than zero provide a filter of opposite hue.
  79221. */
  79222. set: function (value) {
  79223. this._globalDensity = value;
  79224. this._dirty = true;
  79225. },
  79226. enumerable: true,
  79227. configurable: true
  79228. });
  79229. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  79230. /**
  79231. * Gets the global Saturation value.
  79232. * 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.
  79233. */
  79234. get: function () {
  79235. return this._globalSaturation;
  79236. },
  79237. /**
  79238. * Sets the global Saturation value.
  79239. * 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.
  79240. */
  79241. set: function (value) {
  79242. this._globalSaturation = value;
  79243. this._dirty = true;
  79244. },
  79245. enumerable: true,
  79246. configurable: true
  79247. });
  79248. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  79249. /**
  79250. * Gets the global Exposure value.
  79251. * 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.
  79252. */
  79253. get: function () {
  79254. return this._globalExposure;
  79255. },
  79256. /**
  79257. * Sets the global Exposure value.
  79258. * 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.
  79259. */
  79260. set: function (value) {
  79261. this._globalExposure = value;
  79262. this._dirty = true;
  79263. },
  79264. enumerable: true,
  79265. configurable: true
  79266. });
  79267. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  79268. /**
  79269. * Gets the highlights Hue value.
  79270. * 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).
  79271. */
  79272. get: function () {
  79273. return this._highlightsHue;
  79274. },
  79275. /**
  79276. * Sets the highlights Hue value.
  79277. * 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).
  79278. */
  79279. set: function (value) {
  79280. this._highlightsHue = value;
  79281. this._dirty = true;
  79282. },
  79283. enumerable: true,
  79284. configurable: true
  79285. });
  79286. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  79287. /**
  79288. * Gets the highlights Density value.
  79289. * 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.
  79290. * Values less than zero provide a filter of opposite hue.
  79291. */
  79292. get: function () {
  79293. return this._highlightsDensity;
  79294. },
  79295. /**
  79296. * Sets the highlights Density value.
  79297. * 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.
  79298. * Values less than zero provide a filter of opposite hue.
  79299. */
  79300. set: function (value) {
  79301. this._highlightsDensity = value;
  79302. this._dirty = true;
  79303. },
  79304. enumerable: true,
  79305. configurable: true
  79306. });
  79307. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  79308. /**
  79309. * Gets the highlights Saturation value.
  79310. * 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.
  79311. */
  79312. get: function () {
  79313. return this._highlightsSaturation;
  79314. },
  79315. /**
  79316. * Sets the highlights Saturation value.
  79317. * 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.
  79318. */
  79319. set: function (value) {
  79320. this._highlightsSaturation = value;
  79321. this._dirty = true;
  79322. },
  79323. enumerable: true,
  79324. configurable: true
  79325. });
  79326. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  79327. /**
  79328. * Gets the highlights Exposure value.
  79329. * 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.
  79330. */
  79331. get: function () {
  79332. return this._highlightsExposure;
  79333. },
  79334. /**
  79335. * Sets the highlights Exposure value.
  79336. * 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.
  79337. */
  79338. set: function (value) {
  79339. this._highlightsExposure = value;
  79340. this._dirty = true;
  79341. },
  79342. enumerable: true,
  79343. configurable: true
  79344. });
  79345. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  79346. /**
  79347. * Gets the midtones Hue value.
  79348. * 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).
  79349. */
  79350. get: function () {
  79351. return this._midtonesHue;
  79352. },
  79353. /**
  79354. * Sets the midtones Hue value.
  79355. * 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).
  79356. */
  79357. set: function (value) {
  79358. this._midtonesHue = value;
  79359. this._dirty = true;
  79360. },
  79361. enumerable: true,
  79362. configurable: true
  79363. });
  79364. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  79365. /**
  79366. * Gets the midtones Density value.
  79367. * 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.
  79368. * Values less than zero provide a filter of opposite hue.
  79369. */
  79370. get: function () {
  79371. return this._midtonesDensity;
  79372. },
  79373. /**
  79374. * Sets the midtones Density value.
  79375. * 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.
  79376. * Values less than zero provide a filter of opposite hue.
  79377. */
  79378. set: function (value) {
  79379. this._midtonesDensity = value;
  79380. this._dirty = true;
  79381. },
  79382. enumerable: true,
  79383. configurable: true
  79384. });
  79385. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  79386. /**
  79387. * Gets the midtones Saturation value.
  79388. * 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.
  79389. */
  79390. get: function () {
  79391. return this._midtonesSaturation;
  79392. },
  79393. /**
  79394. * Sets the midtones Saturation value.
  79395. * 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.
  79396. */
  79397. set: function (value) {
  79398. this._midtonesSaturation = value;
  79399. this._dirty = true;
  79400. },
  79401. enumerable: true,
  79402. configurable: true
  79403. });
  79404. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  79405. /**
  79406. * Gets the midtones Exposure value.
  79407. * 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.
  79408. */
  79409. get: function () {
  79410. return this._midtonesExposure;
  79411. },
  79412. /**
  79413. * Sets the midtones Exposure value.
  79414. * 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.
  79415. */
  79416. set: function (value) {
  79417. this._midtonesExposure = value;
  79418. this._dirty = true;
  79419. },
  79420. enumerable: true,
  79421. configurable: true
  79422. });
  79423. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  79424. /**
  79425. * Gets the shadows Hue value.
  79426. * 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).
  79427. */
  79428. get: function () {
  79429. return this._shadowsHue;
  79430. },
  79431. /**
  79432. * Sets the shadows Hue value.
  79433. * 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).
  79434. */
  79435. set: function (value) {
  79436. this._shadowsHue = value;
  79437. this._dirty = true;
  79438. },
  79439. enumerable: true,
  79440. configurable: true
  79441. });
  79442. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  79443. /**
  79444. * Gets the shadows Density value.
  79445. * 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.
  79446. * Values less than zero provide a filter of opposite hue.
  79447. */
  79448. get: function () {
  79449. return this._shadowsDensity;
  79450. },
  79451. /**
  79452. * Sets the shadows Density value.
  79453. * 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.
  79454. * Values less than zero provide a filter of opposite hue.
  79455. */
  79456. set: function (value) {
  79457. this._shadowsDensity = value;
  79458. this._dirty = true;
  79459. },
  79460. enumerable: true,
  79461. configurable: true
  79462. });
  79463. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  79464. /**
  79465. * Gets the shadows Saturation value.
  79466. * 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.
  79467. */
  79468. get: function () {
  79469. return this._shadowsSaturation;
  79470. },
  79471. /**
  79472. * Sets the shadows Saturation value.
  79473. * 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.
  79474. */
  79475. set: function (value) {
  79476. this._shadowsSaturation = value;
  79477. this._dirty = true;
  79478. },
  79479. enumerable: true,
  79480. configurable: true
  79481. });
  79482. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  79483. /**
  79484. * Gets the shadows Exposure value.
  79485. * 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.
  79486. */
  79487. get: function () {
  79488. return this._shadowsExposure;
  79489. },
  79490. /**
  79491. * Sets the shadows Exposure value.
  79492. * 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.
  79493. */
  79494. set: function (value) {
  79495. this._shadowsExposure = value;
  79496. this._dirty = true;
  79497. },
  79498. enumerable: true,
  79499. configurable: true
  79500. });
  79501. ColorCurves.prototype.getClassName = function () {
  79502. return "ColorCurves";
  79503. };
  79504. /**
  79505. * Binds the color curves to the shader.
  79506. * @param colorCurves The color curve to bind
  79507. * @param effect The effect to bind to
  79508. */
  79509. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  79510. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  79511. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  79512. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  79513. if (colorCurves._dirty) {
  79514. colorCurves._dirty = false;
  79515. // Fill in global info.
  79516. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  79517. // Compute highlights info.
  79518. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  79519. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  79520. // Compute midtones info.
  79521. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  79522. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  79523. // Compute shadows info.
  79524. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  79525. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  79526. // Compute deltas (neutral is midtones).
  79527. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  79528. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  79529. }
  79530. if (effect) {
  79531. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  79532. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  79533. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  79534. }
  79535. };
  79536. /**
  79537. * Prepare the list of uniforms associated with the ColorCurves effects.
  79538. * @param uniformsList The list of uniforms used in the effect
  79539. */
  79540. ColorCurves.PrepareUniforms = function (uniformsList) {
  79541. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  79542. };
  79543. /**
  79544. * Returns color grading data based on a hue, density, saturation and exposure value.
  79545. * @param filterHue The hue of the color filter.
  79546. * @param filterDensity The density of the color filter.
  79547. * @param saturation The saturation.
  79548. * @param exposure The exposure.
  79549. * @param result The result data container.
  79550. */
  79551. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  79552. if (hue == null) {
  79553. return;
  79554. }
  79555. hue = ColorCurves.clamp(hue, 0, 360);
  79556. density = ColorCurves.clamp(density, -100, 100);
  79557. saturation = ColorCurves.clamp(saturation, -100, 100);
  79558. exposure = ColorCurves.clamp(exposure, -100, 100);
  79559. // Remap the slider/config filter density with non-linear mapping and also scale by half
  79560. // so that the maximum filter density is only 50% control. This provides fine control
  79561. // for small values and reasonable range.
  79562. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  79563. density *= 0.5;
  79564. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  79565. if (density < 0) {
  79566. density *= -1;
  79567. hue = (hue + 180) % 360;
  79568. }
  79569. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  79570. result.scaleToRef(2, result);
  79571. result.a = 1 + 0.01 * saturation;
  79572. };
  79573. /**
  79574. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  79575. * @param value The input slider value in range [-100,100].
  79576. * @returns Adjusted value.
  79577. */
  79578. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  79579. value /= 100;
  79580. var x = Math.abs(value);
  79581. x = Math.pow(x, 2);
  79582. if (value < 0) {
  79583. x *= -1;
  79584. }
  79585. x *= 100;
  79586. return x;
  79587. };
  79588. /**
  79589. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  79590. * @param hue The hue (H) input.
  79591. * @param saturation The saturation (S) input.
  79592. * @param brightness The brightness (B) input.
  79593. * @result An RGBA color represented as Vector4.
  79594. */
  79595. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  79596. var h = ColorCurves.clamp(hue, 0, 360);
  79597. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  79598. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  79599. if (s === 0) {
  79600. result.r = v;
  79601. result.g = v;
  79602. result.b = v;
  79603. }
  79604. else {
  79605. // sector 0 to 5
  79606. h /= 60;
  79607. var i = Math.floor(h);
  79608. // fractional part of h
  79609. var f = h - i;
  79610. var p = v * (1 - s);
  79611. var q = v * (1 - s * f);
  79612. var t = v * (1 - s * (1 - f));
  79613. switch (i) {
  79614. case 0:
  79615. result.r = v;
  79616. result.g = t;
  79617. result.b = p;
  79618. break;
  79619. case 1:
  79620. result.r = q;
  79621. result.g = v;
  79622. result.b = p;
  79623. break;
  79624. case 2:
  79625. result.r = p;
  79626. result.g = v;
  79627. result.b = t;
  79628. break;
  79629. case 3:
  79630. result.r = p;
  79631. result.g = q;
  79632. result.b = v;
  79633. break;
  79634. case 4:
  79635. result.r = t;
  79636. result.g = p;
  79637. result.b = v;
  79638. break;
  79639. default: // case 5:
  79640. result.r = v;
  79641. result.g = p;
  79642. result.b = q;
  79643. break;
  79644. }
  79645. }
  79646. result.a = 1;
  79647. };
  79648. /**
  79649. * Returns a value clamped between min and max
  79650. * @param value The value to clamp
  79651. * @param min The minimum of value
  79652. * @param max The maximum of value
  79653. * @returns The clamped value.
  79654. */
  79655. ColorCurves.clamp = function (value, min, max) {
  79656. return Math.min(Math.max(value, min), max);
  79657. };
  79658. /**
  79659. * Clones the current color curve instance.
  79660. * @return The cloned curves
  79661. */
  79662. ColorCurves.prototype.clone = function () {
  79663. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  79664. };
  79665. /**
  79666. * Serializes the current color curve instance to a json representation.
  79667. * @return a JSON representation
  79668. */
  79669. ColorCurves.prototype.serialize = function () {
  79670. return BABYLON.SerializationHelper.Serialize(this);
  79671. };
  79672. /**
  79673. * Parses the color curve from a json representation.
  79674. * @param source the JSON source to parse
  79675. * @return The parsed curves
  79676. */
  79677. ColorCurves.Parse = function (source) {
  79678. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  79679. };
  79680. __decorate([
  79681. BABYLON.serialize()
  79682. ], ColorCurves.prototype, "_globalHue", void 0);
  79683. __decorate([
  79684. BABYLON.serialize()
  79685. ], ColorCurves.prototype, "_globalDensity", void 0);
  79686. __decorate([
  79687. BABYLON.serialize()
  79688. ], ColorCurves.prototype, "_globalSaturation", void 0);
  79689. __decorate([
  79690. BABYLON.serialize()
  79691. ], ColorCurves.prototype, "_globalExposure", void 0);
  79692. __decorate([
  79693. BABYLON.serialize()
  79694. ], ColorCurves.prototype, "_highlightsHue", void 0);
  79695. __decorate([
  79696. BABYLON.serialize()
  79697. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  79698. __decorate([
  79699. BABYLON.serialize()
  79700. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  79701. __decorate([
  79702. BABYLON.serialize()
  79703. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  79704. __decorate([
  79705. BABYLON.serialize()
  79706. ], ColorCurves.prototype, "_midtonesHue", void 0);
  79707. __decorate([
  79708. BABYLON.serialize()
  79709. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  79710. __decorate([
  79711. BABYLON.serialize()
  79712. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  79713. __decorate([
  79714. BABYLON.serialize()
  79715. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  79716. return ColorCurves;
  79717. }());
  79718. BABYLON.ColorCurves = ColorCurves;
  79719. })(BABYLON || (BABYLON = {}));
  79720. //# sourceMappingURL=babylon.colorCurves.js.map
  79721. var BABYLON;
  79722. (function (BABYLON) {
  79723. var RefractionPostProcess = /** @class */ (function (_super) {
  79724. __extends(RefractionPostProcess, _super);
  79725. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  79726. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  79727. _this.color = color;
  79728. _this.depth = depth;
  79729. _this.colorLevel = colorLevel;
  79730. _this._ownRefractionTexture = true;
  79731. _this.onActivateObservable.add(function (cam) {
  79732. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  79733. });
  79734. _this.onApplyObservable.add(function (effect) {
  79735. effect.setColor3("baseColor", _this.color);
  79736. effect.setFloat("depth", _this.depth);
  79737. effect.setFloat("colorLevel", _this.colorLevel);
  79738. effect.setTexture("refractionSampler", _this._refTexture);
  79739. });
  79740. return _this;
  79741. }
  79742. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  79743. /**
  79744. * Gets or sets the refraction texture
  79745. * Please note that you are responsible for disposing the texture if you set it manually
  79746. */
  79747. get: function () {
  79748. return this._refTexture;
  79749. },
  79750. set: function (value) {
  79751. if (this._refTexture && this._ownRefractionTexture) {
  79752. this._refTexture.dispose();
  79753. }
  79754. this._refTexture = value;
  79755. this._ownRefractionTexture = false;
  79756. },
  79757. enumerable: true,
  79758. configurable: true
  79759. });
  79760. // Methods
  79761. RefractionPostProcess.prototype.dispose = function (camera) {
  79762. if (this._refTexture && this._ownRefractionTexture) {
  79763. this._refTexture.dispose();
  79764. this._refTexture = null;
  79765. }
  79766. _super.prototype.dispose.call(this, camera);
  79767. };
  79768. return RefractionPostProcess;
  79769. }(BABYLON.PostProcess));
  79770. BABYLON.RefractionPostProcess = RefractionPostProcess;
  79771. })(BABYLON || (BABYLON = {}));
  79772. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  79773. var BABYLON;
  79774. (function (BABYLON) {
  79775. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  79776. __extends(BlackAndWhitePostProcess, _super);
  79777. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  79778. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  79779. _this.degree = 1;
  79780. _this.onApplyObservable.add(function (effect) {
  79781. effect.setFloat("degree", _this.degree);
  79782. });
  79783. return _this;
  79784. }
  79785. return BlackAndWhitePostProcess;
  79786. }(BABYLON.PostProcess));
  79787. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  79788. })(BABYLON || (BABYLON = {}));
  79789. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  79790. var BABYLON;
  79791. (function (BABYLON) {
  79792. /**
  79793. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  79794. * input texture to perform effects such as edge detection or sharpening
  79795. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  79796. */
  79797. var ConvolutionPostProcess = /** @class */ (function (_super) {
  79798. __extends(ConvolutionPostProcess, _super);
  79799. /**
  79800. * Creates a new instance ConvolutionPostProcess
  79801. * @param name The name of the effect.
  79802. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  79803. * @param options The required width/height ratio to downsize to before computing the render pass.
  79804. * @param camera The camera to apply the render pass to.
  79805. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79806. * @param engine The engine which the post process will be applied. (default: current engine)
  79807. * @param reusable If the post process can be reused on the same frame. (default: false)
  79808. * @param textureType Type of textures used when performing the post process. (default: 0)
  79809. */
  79810. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  79811. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79812. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79813. _this.kernel = kernel;
  79814. _this.onApply = function (effect) {
  79815. effect.setFloat2("screenSize", _this.width, _this.height);
  79816. effect.setArray("kernel", _this.kernel);
  79817. };
  79818. return _this;
  79819. }
  79820. // Statics
  79821. /**
  79822. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79823. */
  79824. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  79825. /**
  79826. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79827. */
  79828. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  79829. /**
  79830. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79831. */
  79832. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  79833. /**
  79834. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79835. */
  79836. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  79837. /**
  79838. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79839. */
  79840. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  79841. /**
  79842. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79843. */
  79844. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  79845. return ConvolutionPostProcess;
  79846. }(BABYLON.PostProcess));
  79847. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  79848. })(BABYLON || (BABYLON = {}));
  79849. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  79850. var BABYLON;
  79851. (function (BABYLON) {
  79852. var FilterPostProcess = /** @class */ (function (_super) {
  79853. __extends(FilterPostProcess, _super);
  79854. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  79855. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  79856. _this.kernelMatrix = kernelMatrix;
  79857. _this.onApply = function (effect) {
  79858. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  79859. };
  79860. return _this;
  79861. }
  79862. return FilterPostProcess;
  79863. }(BABYLON.PostProcess));
  79864. BABYLON.FilterPostProcess = FilterPostProcess;
  79865. })(BABYLON || (BABYLON = {}));
  79866. //# sourceMappingURL=babylon.filterPostProcess.js.map
  79867. var BABYLON;
  79868. (function (BABYLON) {
  79869. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  79870. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  79871. __extends(VolumetricLightScatteringPostProcess, _super);
  79872. /**
  79873. * @constructor
  79874. * @param {string} name - The post-process name
  79875. * @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)
  79876. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  79877. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  79878. * @param {number} samples - The post-process quality, default 100
  79879. * @param {number} samplingMode - The post-process filtering mode
  79880. * @param {BABYLON.Engine} engine - The babylon engine
  79881. * @param {boolean} reusable - If the post-process is reusable
  79882. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  79883. */
  79884. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  79885. if (samples === void 0) { samples = 100; }
  79886. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79887. 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;
  79888. _this._screenCoordinates = BABYLON.Vector2.Zero();
  79889. /**
  79890. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  79891. */
  79892. _this.customMeshPosition = BABYLON.Vector3.Zero();
  79893. /**
  79894. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  79895. */
  79896. _this.useCustomMeshPosition = false;
  79897. /**
  79898. * If the post-process should inverse the light scattering direction
  79899. */
  79900. _this.invert = true;
  79901. /**
  79902. * Array containing the excluded meshes not rendered in the internal pass
  79903. */
  79904. _this.excludedMeshes = new Array();
  79905. /**
  79906. * Controls the overall intensity of the post-process
  79907. */
  79908. _this.exposure = 0.3;
  79909. /**
  79910. * Dissipates each sample's contribution in range [0, 1]
  79911. */
  79912. _this.decay = 0.96815;
  79913. /**
  79914. * Controls the overall intensity of each sample
  79915. */
  79916. _this.weight = 0.58767;
  79917. /**
  79918. * Controls the density of each sample
  79919. */
  79920. _this.density = 0.926;
  79921. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  79922. engine = scene.getEngine();
  79923. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  79924. // Configure mesh
  79925. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  79926. // Configure
  79927. _this._createPass(scene, ratio.passRatio || ratio);
  79928. _this.onActivate = function (camera) {
  79929. if (!_this.isSupported) {
  79930. _this.dispose(camera);
  79931. }
  79932. _this.onActivate = null;
  79933. };
  79934. _this.onApplyObservable.add(function (effect) {
  79935. _this._updateMeshScreenCoordinates(scene);
  79936. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  79937. effect.setFloat("exposure", _this.exposure);
  79938. effect.setFloat("decay", _this.decay);
  79939. effect.setFloat("weight", _this.weight);
  79940. effect.setFloat("density", _this.density);
  79941. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  79942. });
  79943. return _this;
  79944. }
  79945. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  79946. get: function () {
  79947. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79948. return false;
  79949. },
  79950. set: function (useDiffuseColor) {
  79951. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79952. },
  79953. enumerable: true,
  79954. configurable: true
  79955. });
  79956. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  79957. return "VolumetricLightScatteringPostProcess";
  79958. };
  79959. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  79960. var mesh = subMesh.getMesh();
  79961. // Render this.mesh as default
  79962. if (mesh === this.mesh && mesh.material) {
  79963. return mesh.material.isReady(mesh);
  79964. }
  79965. var defines = [];
  79966. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79967. var material = subMesh.getMaterial();
  79968. // Alpha test
  79969. if (material) {
  79970. if (material.needAlphaTesting()) {
  79971. defines.push("#define ALPHATEST");
  79972. }
  79973. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79974. attribs.push(BABYLON.VertexBuffer.UVKind);
  79975. defines.push("#define UV1");
  79976. }
  79977. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79978. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79979. defines.push("#define UV2");
  79980. }
  79981. }
  79982. // Bones
  79983. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79984. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79985. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79986. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79987. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79988. }
  79989. else {
  79990. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79991. }
  79992. // Instances
  79993. if (useInstances) {
  79994. defines.push("#define INSTANCES");
  79995. attribs.push("world0");
  79996. attribs.push("world1");
  79997. attribs.push("world2");
  79998. attribs.push("world3");
  79999. }
  80000. // Get correct effect
  80001. var join = defines.join("\n");
  80002. if (this._cachedDefines !== join) {
  80003. this._cachedDefines = join;
  80004. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  80005. }
  80006. return this._volumetricLightScatteringPass.isReady();
  80007. };
  80008. /**
  80009. * Sets the new light position for light scattering effect
  80010. * @param {BABYLON.Vector3} The new custom light position
  80011. */
  80012. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  80013. this.customMeshPosition = position;
  80014. };
  80015. /**
  80016. * Returns the light position for light scattering effect
  80017. * @return {BABYLON.Vector3} The custom light position
  80018. */
  80019. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  80020. return this.customMeshPosition;
  80021. };
  80022. /**
  80023. * Disposes the internal assets and detaches the post-process from the camera
  80024. */
  80025. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  80026. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  80027. if (rttIndex !== -1) {
  80028. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  80029. }
  80030. this._volumetricLightScatteringRTT.dispose();
  80031. _super.prototype.dispose.call(this, camera);
  80032. };
  80033. /**
  80034. * Returns the render target texture used by the post-process
  80035. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  80036. */
  80037. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  80038. return this._volumetricLightScatteringRTT;
  80039. };
  80040. // Private methods
  80041. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  80042. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  80043. return true;
  80044. }
  80045. return false;
  80046. };
  80047. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  80048. var _this = this;
  80049. var engine = scene.getEngine();
  80050. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80051. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80052. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80053. this._volumetricLightScatteringRTT.renderList = null;
  80054. this._volumetricLightScatteringRTT.renderParticles = false;
  80055. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  80056. var camera = this.getCamera();
  80057. if (camera) {
  80058. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80059. }
  80060. else {
  80061. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80062. }
  80063. // Custom render function for submeshes
  80064. var renderSubMesh = function (subMesh) {
  80065. var mesh = subMesh.getRenderingMesh();
  80066. if (_this._meshExcluded(mesh)) {
  80067. return;
  80068. }
  80069. var material = subMesh.getMaterial();
  80070. if (!material) {
  80071. return;
  80072. }
  80073. var scene = mesh.getScene();
  80074. var engine = scene.getEngine();
  80075. // Culling
  80076. engine.setState(material.backFaceCulling);
  80077. // Managing instances
  80078. var batch = mesh._getInstancesRenderList(subMesh._id);
  80079. if (batch.mustReturn) {
  80080. return;
  80081. }
  80082. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80083. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  80084. var effect = _this._volumetricLightScatteringPass;
  80085. if (mesh === _this.mesh) {
  80086. if (subMesh.effect) {
  80087. effect = subMesh.effect;
  80088. }
  80089. else {
  80090. effect = material.getEffect();
  80091. }
  80092. }
  80093. engine.enableEffect(effect);
  80094. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  80095. if (mesh === _this.mesh) {
  80096. material.bind(mesh.getWorldMatrix(), mesh);
  80097. }
  80098. else {
  80099. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  80100. // Alpha test
  80101. if (material && material.needAlphaTesting()) {
  80102. var alphaTexture = material.getAlphaTestTexture();
  80103. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  80104. if (alphaTexture) {
  80105. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80106. }
  80107. }
  80108. // Bones
  80109. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80110. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80111. }
  80112. }
  80113. // Draw
  80114. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  80115. }
  80116. };
  80117. // Render target texture callbacks
  80118. var savedSceneClearColor;
  80119. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  80120. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  80121. savedSceneClearColor = scene.clearColor;
  80122. scene.clearColor = sceneClearColor;
  80123. });
  80124. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  80125. scene.clearColor = savedSceneClearColor;
  80126. });
  80127. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80128. var engine = scene.getEngine();
  80129. var index;
  80130. if (depthOnlySubMeshes.length) {
  80131. engine.setColorWrite(false);
  80132. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80133. renderSubMesh(depthOnlySubMeshes.data[index]);
  80134. }
  80135. engine.setColorWrite(true);
  80136. }
  80137. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80138. renderSubMesh(opaqueSubMeshes.data[index]);
  80139. }
  80140. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80141. renderSubMesh(alphaTestSubMeshes.data[index]);
  80142. }
  80143. if (transparentSubMeshes.length) {
  80144. // Sort sub meshes
  80145. for (index = 0; index < transparentSubMeshes.length; index++) {
  80146. var submesh = transparentSubMeshes.data[index];
  80147. var boundingInfo = submesh.getBoundingInfo();
  80148. if (boundingInfo && scene.activeCamera) {
  80149. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  80150. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  80151. }
  80152. }
  80153. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  80154. sortedArray.sort(function (a, b) {
  80155. // Alpha index first
  80156. if (a._alphaIndex > b._alphaIndex) {
  80157. return 1;
  80158. }
  80159. if (a._alphaIndex < b._alphaIndex) {
  80160. return -1;
  80161. }
  80162. // Then distance to camera
  80163. if (a._distanceToCamera < b._distanceToCamera) {
  80164. return 1;
  80165. }
  80166. if (a._distanceToCamera > b._distanceToCamera) {
  80167. return -1;
  80168. }
  80169. return 0;
  80170. });
  80171. // Render sub meshes
  80172. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  80173. for (index = 0; index < sortedArray.length; index++) {
  80174. renderSubMesh(sortedArray[index]);
  80175. }
  80176. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80177. }
  80178. };
  80179. };
  80180. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  80181. var transform = scene.getTransformMatrix();
  80182. var meshPosition;
  80183. if (this.useCustomMeshPosition) {
  80184. meshPosition = this.customMeshPosition;
  80185. }
  80186. else if (this.attachedNode) {
  80187. meshPosition = this.attachedNode.position;
  80188. }
  80189. else {
  80190. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  80191. }
  80192. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  80193. this._screenCoordinates.x = pos.x / this._viewPort.width;
  80194. this._screenCoordinates.y = pos.y / this._viewPort.height;
  80195. if (this.invert)
  80196. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  80197. };
  80198. // Static methods
  80199. /**
  80200. * Creates a default mesh for the Volumeric Light Scattering post-process
  80201. * @param {string} The mesh name
  80202. * @param {BABYLON.Scene} The scene where to create the mesh
  80203. * @return {BABYLON.Mesh} the default mesh
  80204. */
  80205. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  80206. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  80207. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  80208. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  80209. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  80210. mesh.material = material;
  80211. return mesh;
  80212. };
  80213. __decorate([
  80214. BABYLON.serializeAsVector3()
  80215. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  80216. __decorate([
  80217. BABYLON.serialize()
  80218. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  80219. __decorate([
  80220. BABYLON.serialize()
  80221. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  80222. __decorate([
  80223. BABYLON.serializeAsMeshReference()
  80224. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  80225. __decorate([
  80226. BABYLON.serialize()
  80227. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  80228. __decorate([
  80229. BABYLON.serialize()
  80230. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  80231. __decorate([
  80232. BABYLON.serialize()
  80233. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  80234. __decorate([
  80235. BABYLON.serialize()
  80236. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  80237. __decorate([
  80238. BABYLON.serialize()
  80239. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  80240. return VolumetricLightScatteringPostProcess;
  80241. }(BABYLON.PostProcess));
  80242. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  80243. })(BABYLON || (BABYLON = {}));
  80244. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  80245. //
  80246. // This post-process allows the modification of rendered colors by using
  80247. // a 'look-up table' (LUT). This effect is also called Color Grading.
  80248. //
  80249. // The object needs to be provided an url to a texture containing the color
  80250. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  80251. // Use an image editing software to tweak the LUT to match your needs.
  80252. //
  80253. // For an example of a color LUT, see here:
  80254. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  80255. // For explanations on color grading, see here:
  80256. // http://udn.epicgames.com/Three/ColorGrading.html
  80257. //
  80258. var BABYLON;
  80259. (function (BABYLON) {
  80260. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  80261. __extends(ColorCorrectionPostProcess, _super);
  80262. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  80263. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  80264. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80265. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  80266. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80267. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80268. _this.onApply = function (effect) {
  80269. effect.setTexture("colorTable", _this._colorTableTexture);
  80270. };
  80271. return _this;
  80272. }
  80273. return ColorCorrectionPostProcess;
  80274. }(BABYLON.PostProcess));
  80275. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  80276. })(BABYLON || (BABYLON = {}));
  80277. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  80278. var BABYLON;
  80279. (function (BABYLON) {
  80280. /** Defines operator used for tonemapping */
  80281. var TonemappingOperator;
  80282. (function (TonemappingOperator) {
  80283. /** Hable */
  80284. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  80285. /** Reinhard */
  80286. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  80287. /** HejiDawson */
  80288. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  80289. /** Photographic */
  80290. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  80291. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  80292. ;
  80293. /**
  80294. * Defines a post process to apply tone mapping
  80295. */
  80296. var TonemapPostProcess = /** @class */ (function (_super) {
  80297. __extends(TonemapPostProcess, _super);
  80298. /**
  80299. * Creates a new TonemapPostProcess
  80300. * @param name defines the name of the postprocess
  80301. * @param _operator defines the operator to use
  80302. * @param exposureAdjustment defines the required exposure adjustement
  80303. * @param camera defines the camera to use (can be null)
  80304. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  80305. * @param engine defines the hosting engine (can be ignore if camera is set)
  80306. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  80307. */
  80308. function TonemapPostProcess(name, _operator,
  80309. /** Defines the required exposure adjustement */
  80310. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  80311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80312. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80313. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  80314. _this._operator = _operator;
  80315. _this.exposureAdjustment = exposureAdjustment;
  80316. var defines = "#define ";
  80317. if (_this._operator === TonemappingOperator.Hable)
  80318. defines += "HABLE_TONEMAPPING";
  80319. else if (_this._operator === TonemappingOperator.Reinhard)
  80320. defines += "REINHARD_TONEMAPPING";
  80321. else if (_this._operator === TonemappingOperator.HejiDawson)
  80322. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  80323. else if (_this._operator === TonemappingOperator.Photographic)
  80324. defines += "PHOTOGRAPHIC_TONEMAPPING";
  80325. //sadly a second call to create the effect.
  80326. _this.updateEffect(defines);
  80327. _this.onApply = function (effect) {
  80328. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  80329. };
  80330. return _this;
  80331. }
  80332. return TonemapPostProcess;
  80333. }(BABYLON.PostProcess));
  80334. BABYLON.TonemapPostProcess = TonemapPostProcess;
  80335. })(BABYLON || (BABYLON = {}));
  80336. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  80337. var BABYLON;
  80338. (function (BABYLON) {
  80339. var DisplayPassPostProcess = /** @class */ (function (_super) {
  80340. __extends(DisplayPassPostProcess, _super);
  80341. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  80342. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  80343. }
  80344. return DisplayPassPostProcess;
  80345. }(BABYLON.PostProcess));
  80346. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  80347. })(BABYLON || (BABYLON = {}));
  80348. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  80349. var BABYLON;
  80350. (function (BABYLON) {
  80351. var HighlightsPostProcess = /** @class */ (function (_super) {
  80352. __extends(HighlightsPostProcess, _super);
  80353. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80354. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80355. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80356. }
  80357. return HighlightsPostProcess;
  80358. }(BABYLON.PostProcess));
  80359. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  80360. })(BABYLON || (BABYLON = {}));
  80361. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  80362. var BABYLON;
  80363. (function (BABYLON) {
  80364. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  80365. __extends(ImageProcessingPostProcess, _super);
  80366. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  80367. if (camera === void 0) { camera = null; }
  80368. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80369. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  80370. _this._fromLinearSpace = true;
  80371. /**
  80372. * Defines cache preventing GC.
  80373. */
  80374. _this._defines = {
  80375. IMAGEPROCESSING: false,
  80376. VIGNETTE: false,
  80377. VIGNETTEBLENDMODEMULTIPLY: false,
  80378. VIGNETTEBLENDMODEOPAQUE: false,
  80379. TONEMAPPING: false,
  80380. CONTRAST: false,
  80381. COLORCURVES: false,
  80382. COLORGRADING: false,
  80383. COLORGRADING3D: false,
  80384. FROMLINEARSPACE: false,
  80385. SAMPLER3DGREENDEPTH: false,
  80386. SAMPLER3DBGRMAP: false,
  80387. IMAGEPROCESSINGPOSTPROCESS: false,
  80388. EXPOSURE: false,
  80389. };
  80390. // Setup the configuration as forced by the constructor. This would then not force the
  80391. // scene materials output in linear space and let untouched the default forward pass.
  80392. if (imageProcessingConfiguration) {
  80393. imageProcessingConfiguration.applyByPostProcess = true;
  80394. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  80395. // This will cause the shader to be compiled
  80396. _this.fromLinearSpace = false;
  80397. }
  80398. // Setup the default processing configuration to the scene.
  80399. else {
  80400. _this._attachImageProcessingConfiguration(null, true);
  80401. _this.imageProcessingConfiguration.applyByPostProcess = true;
  80402. }
  80403. _this.onApply = function (effect) {
  80404. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  80405. };
  80406. return _this;
  80407. }
  80408. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  80409. /**
  80410. * Gets the image processing configuration used either in this material.
  80411. */
  80412. get: function () {
  80413. return this._imageProcessingConfiguration;
  80414. },
  80415. /**
  80416. * Sets the Default image processing configuration used either in the this material.
  80417. *
  80418. * If sets to null, the scene one is in use.
  80419. */
  80420. set: function (value) {
  80421. this._attachImageProcessingConfiguration(value);
  80422. },
  80423. enumerable: true,
  80424. configurable: true
  80425. });
  80426. /**
  80427. * Attaches a new image processing configuration to the PBR Material.
  80428. * @param configuration
  80429. */
  80430. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  80431. var _this = this;
  80432. if (doNotBuild === void 0) { doNotBuild = false; }
  80433. if (configuration === this._imageProcessingConfiguration) {
  80434. return;
  80435. }
  80436. // Detaches observer.
  80437. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80438. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80439. }
  80440. // Pick the scene configuration if needed.
  80441. if (!configuration) {
  80442. var scene = null;
  80443. var engine = this.getEngine();
  80444. var camera = this.getCamera();
  80445. if (camera) {
  80446. scene = camera.getScene();
  80447. }
  80448. else if (engine && engine.scenes) {
  80449. var scenes = engine.scenes;
  80450. scene = scenes[scenes.length - 1];
  80451. }
  80452. else {
  80453. scene = BABYLON.Engine.LastCreatedScene;
  80454. }
  80455. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  80456. }
  80457. else {
  80458. this._imageProcessingConfiguration = configuration;
  80459. }
  80460. // Attaches observer.
  80461. if (this._imageProcessingConfiguration) {
  80462. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80463. _this._updateParameters();
  80464. });
  80465. }
  80466. // Ensure the effect will be rebuilt.
  80467. if (!doNotBuild) {
  80468. this._updateParameters();
  80469. }
  80470. };
  80471. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  80472. /**
  80473. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80474. */
  80475. get: function () {
  80476. return this.imageProcessingConfiguration.colorCurves;
  80477. },
  80478. /**
  80479. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80480. */
  80481. set: function (value) {
  80482. this.imageProcessingConfiguration.colorCurves = value;
  80483. },
  80484. enumerable: true,
  80485. configurable: true
  80486. });
  80487. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  80488. /**
  80489. * Gets wether the color curves effect is enabled.
  80490. */
  80491. get: function () {
  80492. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80493. },
  80494. /**
  80495. * Sets wether the color curves effect is enabled.
  80496. */
  80497. set: function (value) {
  80498. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80499. },
  80500. enumerable: true,
  80501. configurable: true
  80502. });
  80503. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  80504. /**
  80505. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80506. */
  80507. get: function () {
  80508. return this.imageProcessingConfiguration.colorGradingTexture;
  80509. },
  80510. /**
  80511. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80512. */
  80513. set: function (value) {
  80514. this.imageProcessingConfiguration.colorGradingTexture = value;
  80515. },
  80516. enumerable: true,
  80517. configurable: true
  80518. });
  80519. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  80520. /**
  80521. * Gets wether the color grading effect is enabled.
  80522. */
  80523. get: function () {
  80524. return this.imageProcessingConfiguration.colorGradingEnabled;
  80525. },
  80526. /**
  80527. * Gets wether the color grading effect is enabled.
  80528. */
  80529. set: function (value) {
  80530. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80531. },
  80532. enumerable: true,
  80533. configurable: true
  80534. });
  80535. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  80536. /**
  80537. * Gets exposure used in the effect.
  80538. */
  80539. get: function () {
  80540. return this.imageProcessingConfiguration.exposure;
  80541. },
  80542. /**
  80543. * Sets exposure used in the effect.
  80544. */
  80545. set: function (value) {
  80546. this.imageProcessingConfiguration.exposure = value;
  80547. },
  80548. enumerable: true,
  80549. configurable: true
  80550. });
  80551. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  80552. /**
  80553. * Gets wether tonemapping is enabled or not.
  80554. */
  80555. get: function () {
  80556. return this._imageProcessingConfiguration.toneMappingEnabled;
  80557. },
  80558. /**
  80559. * Sets wether tonemapping is enabled or not
  80560. */
  80561. set: function (value) {
  80562. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80563. },
  80564. enumerable: true,
  80565. configurable: true
  80566. });
  80567. ;
  80568. ;
  80569. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  80570. /**
  80571. * Gets contrast used in the effect.
  80572. */
  80573. get: function () {
  80574. return this.imageProcessingConfiguration.contrast;
  80575. },
  80576. /**
  80577. * Sets contrast used in the effect.
  80578. */
  80579. set: function (value) {
  80580. this.imageProcessingConfiguration.contrast = value;
  80581. },
  80582. enumerable: true,
  80583. configurable: true
  80584. });
  80585. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  80586. /**
  80587. * Gets Vignette stretch size.
  80588. */
  80589. get: function () {
  80590. return this.imageProcessingConfiguration.vignetteStretch;
  80591. },
  80592. /**
  80593. * Sets Vignette stretch size.
  80594. */
  80595. set: function (value) {
  80596. this.imageProcessingConfiguration.vignetteStretch = value;
  80597. },
  80598. enumerable: true,
  80599. configurable: true
  80600. });
  80601. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  80602. /**
  80603. * Gets Vignette centre X Offset.
  80604. */
  80605. get: function () {
  80606. return this.imageProcessingConfiguration.vignetteCentreX;
  80607. },
  80608. /**
  80609. * Sets Vignette centre X Offset.
  80610. */
  80611. set: function (value) {
  80612. this.imageProcessingConfiguration.vignetteCentreX = value;
  80613. },
  80614. enumerable: true,
  80615. configurable: true
  80616. });
  80617. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  80618. /**
  80619. * Gets Vignette centre Y Offset.
  80620. */
  80621. get: function () {
  80622. return this.imageProcessingConfiguration.vignetteCentreY;
  80623. },
  80624. /**
  80625. * Sets Vignette centre Y Offset.
  80626. */
  80627. set: function (value) {
  80628. this.imageProcessingConfiguration.vignetteCentreY = value;
  80629. },
  80630. enumerable: true,
  80631. configurable: true
  80632. });
  80633. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  80634. /**
  80635. * Gets Vignette weight or intensity of the vignette effect.
  80636. */
  80637. get: function () {
  80638. return this.imageProcessingConfiguration.vignetteWeight;
  80639. },
  80640. /**
  80641. * Sets Vignette weight or intensity of the vignette effect.
  80642. */
  80643. set: function (value) {
  80644. this.imageProcessingConfiguration.vignetteWeight = value;
  80645. },
  80646. enumerable: true,
  80647. configurable: true
  80648. });
  80649. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  80650. /**
  80651. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80652. * if vignetteEnabled is set to true.
  80653. */
  80654. get: function () {
  80655. return this.imageProcessingConfiguration.vignetteColor;
  80656. },
  80657. /**
  80658. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80659. * if vignetteEnabled is set to true.
  80660. */
  80661. set: function (value) {
  80662. this.imageProcessingConfiguration.vignetteColor = value;
  80663. },
  80664. enumerable: true,
  80665. configurable: true
  80666. });
  80667. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  80668. /**
  80669. * Gets Camera field of view used by the Vignette effect.
  80670. */
  80671. get: function () {
  80672. return this.imageProcessingConfiguration.vignetteCameraFov;
  80673. },
  80674. /**
  80675. * Sets Camera field of view used by the Vignette effect.
  80676. */
  80677. set: function (value) {
  80678. this.imageProcessingConfiguration.vignetteCameraFov = value;
  80679. },
  80680. enumerable: true,
  80681. configurable: true
  80682. });
  80683. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  80684. /**
  80685. * Gets the vignette blend mode allowing different kind of effect.
  80686. */
  80687. get: function () {
  80688. return this.imageProcessingConfiguration.vignetteBlendMode;
  80689. },
  80690. /**
  80691. * Sets the vignette blend mode allowing different kind of effect.
  80692. */
  80693. set: function (value) {
  80694. this.imageProcessingConfiguration.vignetteBlendMode = value;
  80695. },
  80696. enumerable: true,
  80697. configurable: true
  80698. });
  80699. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  80700. /**
  80701. * Gets wether the vignette effect is enabled.
  80702. */
  80703. get: function () {
  80704. return this.imageProcessingConfiguration.vignetteEnabled;
  80705. },
  80706. /**
  80707. * Sets wether the vignette effect is enabled.
  80708. */
  80709. set: function (value) {
  80710. this.imageProcessingConfiguration.vignetteEnabled = value;
  80711. },
  80712. enumerable: true,
  80713. configurable: true
  80714. });
  80715. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  80716. /**
  80717. * Gets wether the input of the processing is in Gamma or Linear Space.
  80718. */
  80719. get: function () {
  80720. return this._fromLinearSpace;
  80721. },
  80722. /**
  80723. * Sets wether the input of the processing is in Gamma or Linear Space.
  80724. */
  80725. set: function (value) {
  80726. if (this._fromLinearSpace === value) {
  80727. return;
  80728. }
  80729. this._fromLinearSpace = value;
  80730. this._updateParameters();
  80731. },
  80732. enumerable: true,
  80733. configurable: true
  80734. });
  80735. ImageProcessingPostProcess.prototype.getClassName = function () {
  80736. return "ImageProcessingPostProcess";
  80737. };
  80738. ImageProcessingPostProcess.prototype._updateParameters = function () {
  80739. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  80740. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  80741. var defines = "";
  80742. for (var define in this._defines) {
  80743. if (this._defines[define]) {
  80744. defines += "#define " + define + ";\r\n";
  80745. }
  80746. }
  80747. var samplers = ["textureSampler"];
  80748. var uniforms = ["scale"];
  80749. if (BABYLON.ImageProcessingConfiguration) {
  80750. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  80751. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  80752. }
  80753. this.updateEffect(defines, uniforms, samplers);
  80754. };
  80755. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  80756. _super.prototype.dispose.call(this, camera);
  80757. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80758. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80759. }
  80760. if (this._imageProcessingConfiguration) {
  80761. this.imageProcessingConfiguration.applyByPostProcess = false;
  80762. }
  80763. };
  80764. __decorate([
  80765. BABYLON.serialize()
  80766. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  80767. return ImageProcessingPostProcess;
  80768. }(BABYLON.PostProcess));
  80769. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  80770. })(BABYLON || (BABYLON = {}));
  80771. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  80772. var BABYLON;
  80773. (function (BABYLON) {
  80774. /**
  80775. * Class used to store bone information
  80776. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80777. */
  80778. var Bone = /** @class */ (function (_super) {
  80779. __extends(Bone, _super);
  80780. /**
  80781. * Create a new bone
  80782. * @param name defines the bone name
  80783. * @param skeleton defines the parent skeleton
  80784. * @param parentBone defines the parent (can be null if the bone is the root)
  80785. * @param localMatrix defines the local matrix
  80786. * @param restPose defines the rest pose matrix
  80787. * @param baseMatrix defines the base matrix
  80788. * @param index defines index of the bone in the hiearchy
  80789. */
  80790. function Bone(
  80791. /**
  80792. * defines the bone name
  80793. */
  80794. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  80795. if (parentBone === void 0) { parentBone = null; }
  80796. if (localMatrix === void 0) { localMatrix = null; }
  80797. if (restPose === void 0) { restPose = null; }
  80798. if (baseMatrix === void 0) { baseMatrix = null; }
  80799. if (index === void 0) { index = null; }
  80800. var _this = _super.call(this, name, skeleton.getScene()) || this;
  80801. _this.name = name;
  80802. /**
  80803. * Gets the list of child bones
  80804. */
  80805. _this.children = new Array();
  80806. /** Gets the animations associated with this bone */
  80807. _this.animations = new Array();
  80808. /**
  80809. * @hidden Internal only
  80810. * Set this value to map this bone to a different index in the transform matrices
  80811. * Set this value to -1 to exclude the bone from the transform matrices
  80812. */
  80813. _this._index = null;
  80814. _this._absoluteTransform = new BABYLON.Matrix();
  80815. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  80816. _this._scalingDeterminant = 1;
  80817. _this._worldTransform = new BABYLON.Matrix();
  80818. _this._needToDecompose = true;
  80819. _this._needToCompose = false;
  80820. _this._skeleton = skeleton;
  80821. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  80822. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  80823. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  80824. _this._index = index;
  80825. skeleton.bones.push(_this);
  80826. _this.setParent(parentBone, false);
  80827. if (baseMatrix || localMatrix) {
  80828. _this._updateDifferenceMatrix();
  80829. }
  80830. return _this;
  80831. }
  80832. Object.defineProperty(Bone.prototype, "_matrix", {
  80833. /** @hidden */
  80834. get: function () {
  80835. this._compose();
  80836. return this._localMatrix;
  80837. },
  80838. /** @hidden */
  80839. set: function (value) {
  80840. this._localMatrix.copyFrom(value);
  80841. this._needToDecompose = true;
  80842. },
  80843. enumerable: true,
  80844. configurable: true
  80845. });
  80846. // Members
  80847. /**
  80848. * Gets the parent skeleton
  80849. * @returns a skeleton
  80850. */
  80851. Bone.prototype.getSkeleton = function () {
  80852. return this._skeleton;
  80853. };
  80854. /**
  80855. * Gets parent bone
  80856. * @returns a bone or null if the bone is the root of the bone hierarchy
  80857. */
  80858. Bone.prototype.getParent = function () {
  80859. return this._parent;
  80860. };
  80861. /**
  80862. * Sets the parent bone
  80863. * @param parent defines the parent (can be null if the bone is the root)
  80864. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80865. */
  80866. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  80867. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80868. if (this._parent === parent) {
  80869. return;
  80870. }
  80871. if (this._parent) {
  80872. var index = this._parent.children.indexOf(this);
  80873. if (index !== -1) {
  80874. this._parent.children.splice(index, 1);
  80875. }
  80876. }
  80877. this._parent = parent;
  80878. if (this._parent) {
  80879. this._parent.children.push(this);
  80880. }
  80881. if (updateDifferenceMatrix) {
  80882. this._updateDifferenceMatrix();
  80883. }
  80884. this.markAsDirty();
  80885. };
  80886. /**
  80887. * Gets the local matrix
  80888. * @returns a matrix
  80889. */
  80890. Bone.prototype.getLocalMatrix = function () {
  80891. this._compose();
  80892. return this._localMatrix;
  80893. };
  80894. /**
  80895. * Gets the base matrix (initial matrix which remains unchanged)
  80896. * @returns a matrix
  80897. */
  80898. Bone.prototype.getBaseMatrix = function () {
  80899. return this._baseMatrix;
  80900. };
  80901. /**
  80902. * Gets the rest pose matrix
  80903. * @returns a matrix
  80904. */
  80905. Bone.prototype.getRestPose = function () {
  80906. return this._restPose;
  80907. };
  80908. /**
  80909. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  80910. */
  80911. Bone.prototype.getWorldMatrix = function () {
  80912. return this._worldTransform;
  80913. };
  80914. /**
  80915. * Sets the local matrix to rest pose matrix
  80916. */
  80917. Bone.prototype.returnToRest = function () {
  80918. this.updateMatrix(this._restPose.clone());
  80919. };
  80920. /**
  80921. * Gets the inverse of the absolute transform matrix.
  80922. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  80923. * @returns a matrix
  80924. */
  80925. Bone.prototype.getInvertedAbsoluteTransform = function () {
  80926. return this._invertedAbsoluteTransform;
  80927. };
  80928. /**
  80929. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  80930. * @returns a matrix
  80931. */
  80932. Bone.prototype.getAbsoluteTransform = function () {
  80933. return this._absoluteTransform;
  80934. };
  80935. Object.defineProperty(Bone.prototype, "position", {
  80936. // Properties (matches AbstractMesh properties)
  80937. /** Gets or sets current position (in local space) */
  80938. get: function () {
  80939. this._decompose();
  80940. return this._localPosition;
  80941. },
  80942. set: function (newPosition) {
  80943. this._decompose();
  80944. this._localPosition.copyFrom(newPosition);
  80945. this._markAsDirtyAndCompose();
  80946. },
  80947. enumerable: true,
  80948. configurable: true
  80949. });
  80950. Object.defineProperty(Bone.prototype, "rotation", {
  80951. /** Gets or sets current rotation (in local space) */
  80952. get: function () {
  80953. return this.getRotation();
  80954. },
  80955. set: function (newRotation) {
  80956. this.setRotation(newRotation);
  80957. },
  80958. enumerable: true,
  80959. configurable: true
  80960. });
  80961. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  80962. /** Gets or sets current rotation quaternion (in local space) */
  80963. get: function () {
  80964. this._decompose();
  80965. return this._localRotation;
  80966. },
  80967. set: function (newRotation) {
  80968. this.setRotationQuaternion(newRotation);
  80969. },
  80970. enumerable: true,
  80971. configurable: true
  80972. });
  80973. Object.defineProperty(Bone.prototype, "scaling", {
  80974. /** Gets or sets current scaling (in local space) */
  80975. get: function () {
  80976. return this.getScale();
  80977. },
  80978. set: function (newScaling) {
  80979. this.setScale(newScaling);
  80980. },
  80981. enumerable: true,
  80982. configurable: true
  80983. });
  80984. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  80985. /**
  80986. * Gets the animation properties override
  80987. */
  80988. get: function () {
  80989. return this._skeleton.animationPropertiesOverride;
  80990. },
  80991. enumerable: true,
  80992. configurable: true
  80993. });
  80994. // Methods
  80995. Bone.prototype._decompose = function () {
  80996. if (!this._needToDecompose) {
  80997. return;
  80998. }
  80999. this._needToDecompose = false;
  81000. if (!this._localScaling) {
  81001. this._localScaling = BABYLON.Vector3.Zero();
  81002. this._localRotation = BABYLON.Quaternion.Zero();
  81003. this._localPosition = BABYLON.Vector3.Zero();
  81004. }
  81005. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  81006. };
  81007. Bone.prototype._compose = function () {
  81008. if (!this._needToCompose) {
  81009. return;
  81010. }
  81011. this._needToCompose = false;
  81012. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  81013. };
  81014. /**
  81015. * Update the base and local matrices
  81016. * @param matrix defines the new base or local matrix
  81017. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81018. * @param updateLocalMatrix defines if the local matrix should be updated
  81019. */
  81020. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  81021. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81022. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  81023. this._baseMatrix.copyFrom(matrix);
  81024. if (updateDifferenceMatrix) {
  81025. this._updateDifferenceMatrix();
  81026. }
  81027. if (updateLocalMatrix) {
  81028. this._localMatrix.copyFrom(matrix);
  81029. this._markAsDirtyAndDecompose();
  81030. }
  81031. else {
  81032. this.markAsDirty();
  81033. }
  81034. };
  81035. /** @hidden */
  81036. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  81037. if (updateChildren === void 0) { updateChildren = true; }
  81038. if (!rootMatrix) {
  81039. rootMatrix = this._baseMatrix;
  81040. }
  81041. if (this._parent) {
  81042. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81043. }
  81044. else {
  81045. this._absoluteTransform.copyFrom(rootMatrix);
  81046. }
  81047. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  81048. if (updateChildren) {
  81049. for (var index = 0; index < this.children.length; index++) {
  81050. this.children[index]._updateDifferenceMatrix();
  81051. }
  81052. }
  81053. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  81054. };
  81055. /**
  81056. * Flag the bone as dirty (Forcing it to update everything)
  81057. */
  81058. Bone.prototype.markAsDirty = function () {
  81059. this._currentRenderId++;
  81060. this._childRenderId++;
  81061. this._skeleton._markAsDirty();
  81062. };
  81063. Bone.prototype._markAsDirtyAndCompose = function () {
  81064. this.markAsDirty();
  81065. this._needToCompose = true;
  81066. };
  81067. Bone.prototype._markAsDirtyAndDecompose = function () {
  81068. this.markAsDirty();
  81069. this._needToDecompose = true;
  81070. };
  81071. /**
  81072. * Copy an animation range from another bone
  81073. * @param source defines the source bone
  81074. * @param rangeName defines the range name to copy
  81075. * @param frameOffset defines the frame offset
  81076. * @param rescaleAsRequired defines if rescaling must be applied if required
  81077. * @param skelDimensionsRatio defines the scaling ratio
  81078. * @returns true if operation was successful
  81079. */
  81080. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  81081. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81082. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  81083. // all animation may be coming from a library skeleton, so may need to create animation
  81084. if (this.animations.length === 0) {
  81085. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  81086. this.animations[0].setKeys([]);
  81087. }
  81088. // get animation info / verify there is such a range from the source bone
  81089. var sourceRange = source.animations[0].getRange(rangeName);
  81090. if (!sourceRange) {
  81091. return false;
  81092. }
  81093. var from = sourceRange.from;
  81094. var to = sourceRange.to;
  81095. var sourceKeys = source.animations[0].getKeys();
  81096. // rescaling prep
  81097. var sourceBoneLength = source.length;
  81098. var sourceParent = source.getParent();
  81099. var parent = this.getParent();
  81100. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  81101. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  81102. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  81103. var destKeys = this.animations[0].getKeys();
  81104. // loop vars declaration
  81105. var orig;
  81106. var origTranslation;
  81107. var mat;
  81108. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  81109. orig = sourceKeys[key];
  81110. if (orig.frame >= from && orig.frame <= to) {
  81111. if (rescaleAsRequired) {
  81112. mat = orig.value.clone();
  81113. // scale based on parent ratio, when bone has parent
  81114. if (parentScalingReqd) {
  81115. origTranslation = mat.getTranslation();
  81116. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  81117. // scale based on skeleton dimension ratio when root bone, and value is passed
  81118. }
  81119. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  81120. origTranslation = mat.getTranslation();
  81121. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  81122. // use original when root bone, and no data for skelDimensionsRatio
  81123. }
  81124. else {
  81125. mat = orig.value;
  81126. }
  81127. }
  81128. else {
  81129. mat = orig.value;
  81130. }
  81131. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  81132. }
  81133. }
  81134. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  81135. return true;
  81136. };
  81137. /**
  81138. * Translate the bone in local or world space
  81139. * @param vec The amount to translate the bone
  81140. * @param space The space that the translation is in
  81141. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81142. */
  81143. Bone.prototype.translate = function (vec, space, mesh) {
  81144. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81145. var lm = this.getLocalMatrix();
  81146. if (space == BABYLON.Space.LOCAL) {
  81147. lm.m[12] += vec.x;
  81148. lm.m[13] += vec.y;
  81149. lm.m[14] += vec.z;
  81150. }
  81151. else {
  81152. var wm = null;
  81153. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81154. if (mesh) {
  81155. wm = mesh.getWorldMatrix();
  81156. }
  81157. this._skeleton.computeAbsoluteTransforms();
  81158. var tmat = Bone._tmpMats[0];
  81159. var tvec = Bone._tmpVecs[0];
  81160. if (this._parent) {
  81161. if (mesh && wm) {
  81162. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81163. tmat.multiplyToRef(wm, tmat);
  81164. }
  81165. else {
  81166. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81167. }
  81168. }
  81169. tmat.m[12] = 0;
  81170. tmat.m[13] = 0;
  81171. tmat.m[14] = 0;
  81172. tmat.invert();
  81173. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  81174. lm.m[12] += tvec.x;
  81175. lm.m[13] += tvec.y;
  81176. lm.m[14] += tvec.z;
  81177. }
  81178. this._markAsDirtyAndDecompose();
  81179. };
  81180. /**
  81181. * Set the postion of the bone in local or world space
  81182. * @param position The position to set the bone
  81183. * @param space The space that the position is in
  81184. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81185. */
  81186. Bone.prototype.setPosition = function (position, space, mesh) {
  81187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81188. var lm = this.getLocalMatrix();
  81189. if (space == BABYLON.Space.LOCAL) {
  81190. lm.m[12] = position.x;
  81191. lm.m[13] = position.y;
  81192. lm.m[14] = position.z;
  81193. }
  81194. else {
  81195. var wm = null;
  81196. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81197. if (mesh) {
  81198. wm = mesh.getWorldMatrix();
  81199. }
  81200. this._skeleton.computeAbsoluteTransforms();
  81201. var tmat = Bone._tmpMats[0];
  81202. var vec = Bone._tmpVecs[0];
  81203. if (this._parent) {
  81204. if (mesh && wm) {
  81205. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81206. tmat.multiplyToRef(wm, tmat);
  81207. }
  81208. else {
  81209. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81210. }
  81211. }
  81212. tmat.invert();
  81213. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  81214. lm.m[12] = vec.x;
  81215. lm.m[13] = vec.y;
  81216. lm.m[14] = vec.z;
  81217. }
  81218. this._markAsDirtyAndDecompose();
  81219. };
  81220. /**
  81221. * Set the absolute position of the bone (world space)
  81222. * @param position The position to set the bone
  81223. * @param mesh The mesh that this bone is attached to
  81224. */
  81225. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  81226. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  81227. };
  81228. /**
  81229. * Scale the bone on the x, y and z axes (in local space)
  81230. * @param x The amount to scale the bone on the x axis
  81231. * @param y The amount to scale the bone on the y axis
  81232. * @param z The amount to scale the bone on the z axis
  81233. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  81234. */
  81235. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  81236. if (scaleChildren === void 0) { scaleChildren = false; }
  81237. var locMat = this.getLocalMatrix();
  81238. // Apply new scaling on top of current local matrix
  81239. var scaleMat = Bone._tmpMats[0];
  81240. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  81241. scaleMat.multiplyToRef(locMat, locMat);
  81242. // Invert scaling matrix and apply the inverse to all children
  81243. scaleMat.invert();
  81244. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  81245. var child = _a[_i];
  81246. var cm = child.getLocalMatrix();
  81247. cm.multiplyToRef(scaleMat, cm);
  81248. cm.m[12] *= x;
  81249. cm.m[13] *= y;
  81250. cm.m[14] *= z;
  81251. child._markAsDirtyAndDecompose();
  81252. }
  81253. this._markAsDirtyAndDecompose();
  81254. if (scaleChildren) {
  81255. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  81256. var child = _c[_b];
  81257. child.scale(x, y, z, scaleChildren);
  81258. }
  81259. }
  81260. };
  81261. /**
  81262. * Set the bone scaling in local space
  81263. * @param scale defines the scaling vector
  81264. */
  81265. Bone.prototype.setScale = function (scale) {
  81266. this._decompose();
  81267. this._localScaling.copyFrom(scale);
  81268. this._markAsDirtyAndCompose();
  81269. };
  81270. /**
  81271. * Gets the current scaling in local space
  81272. * @returns the current scaling vector
  81273. */
  81274. Bone.prototype.getScale = function () {
  81275. this._decompose();
  81276. return this._localScaling;
  81277. };
  81278. /**
  81279. * Gets the current scaling in local space and stores it in a target vector
  81280. * @param result defines the target vector
  81281. */
  81282. Bone.prototype.getScaleToRef = function (result) {
  81283. this._decompose();
  81284. result.copyFrom(this._localScaling);
  81285. };
  81286. /**
  81287. * Set the yaw, pitch, and roll of the bone in local or world space
  81288. * @param yaw The rotation of the bone on the y axis
  81289. * @param pitch The rotation of the bone on the x axis
  81290. * @param roll The rotation of the bone on the z axis
  81291. * @param space The space that the axes of rotation are in
  81292. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81293. */
  81294. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  81295. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81296. if (space === BABYLON.Space.LOCAL) {
  81297. var quat = Bone._tmpQuat;
  81298. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  81299. this.setRotationQuaternion(quat, space, mesh);
  81300. return;
  81301. }
  81302. var rotMatInv = Bone._tmpMats[0];
  81303. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81304. return;
  81305. }
  81306. var rotMat = Bone._tmpMats[1];
  81307. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  81308. rotMatInv.multiplyToRef(rotMat, rotMat);
  81309. this._rotateWithMatrix(rotMat, space, mesh);
  81310. };
  81311. /**
  81312. * Add a rotation to the bone on an axis in local or world space
  81313. * @param axis The axis to rotate the bone on
  81314. * @param amount The amount to rotate the bone
  81315. * @param space The space that the axis is in
  81316. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81317. */
  81318. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  81319. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81320. var rmat = Bone._tmpMats[0];
  81321. rmat.m[12] = 0;
  81322. rmat.m[13] = 0;
  81323. rmat.m[14] = 0;
  81324. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  81325. this._rotateWithMatrix(rmat, space, mesh);
  81326. };
  81327. /**
  81328. * Set the rotation of the bone to a particular axis angle in local or world space
  81329. * @param axis The axis to rotate the bone on
  81330. * @param angle The angle that the bone should be rotated to
  81331. * @param space The space that the axis is in
  81332. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81333. */
  81334. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  81335. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81336. if (space === BABYLON.Space.LOCAL) {
  81337. var quat = Bone._tmpQuat;
  81338. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  81339. this.setRotationQuaternion(quat, space, mesh);
  81340. return;
  81341. }
  81342. var rotMatInv = Bone._tmpMats[0];
  81343. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81344. return;
  81345. }
  81346. var rotMat = Bone._tmpMats[1];
  81347. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  81348. rotMatInv.multiplyToRef(rotMat, rotMat);
  81349. this._rotateWithMatrix(rotMat, space, mesh);
  81350. };
  81351. /**
  81352. * Set the euler rotation of the bone in local of world space
  81353. * @param rotation The euler rotation that the bone should be set to
  81354. * @param space The space that the rotation is in
  81355. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81356. */
  81357. Bone.prototype.setRotation = function (rotation, space, mesh) {
  81358. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81359. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  81360. };
  81361. /**
  81362. * Set the quaternion rotation of the bone in local of world space
  81363. * @param quat The quaternion rotation that the bone should be set to
  81364. * @param space The space that the rotation is in
  81365. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81366. */
  81367. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  81368. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81369. if (space === BABYLON.Space.LOCAL) {
  81370. this._decompose();
  81371. this._localRotation.copyFrom(quat);
  81372. this._markAsDirtyAndCompose();
  81373. return;
  81374. }
  81375. var rotMatInv = Bone._tmpMats[0];
  81376. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81377. return;
  81378. }
  81379. var rotMat = Bone._tmpMats[1];
  81380. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  81381. rotMatInv.multiplyToRef(rotMat, rotMat);
  81382. this._rotateWithMatrix(rotMat, space, mesh);
  81383. };
  81384. /**
  81385. * Set the rotation matrix of the bone in local of world space
  81386. * @param rotMat The rotation matrix that the bone should be set to
  81387. * @param space The space that the rotation is in
  81388. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81389. */
  81390. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  81391. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81392. if (space === BABYLON.Space.LOCAL) {
  81393. var quat = Bone._tmpQuat;
  81394. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  81395. this.setRotationQuaternion(quat, space, mesh);
  81396. return;
  81397. }
  81398. var rotMatInv = Bone._tmpMats[0];
  81399. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81400. return;
  81401. }
  81402. var rotMat2 = Bone._tmpMats[1];
  81403. rotMat2.copyFrom(rotMat);
  81404. rotMatInv.multiplyToRef(rotMat, rotMat2);
  81405. this._rotateWithMatrix(rotMat2, space, mesh);
  81406. };
  81407. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  81408. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81409. var lmat = this.getLocalMatrix();
  81410. var lx = lmat.m[12];
  81411. var ly = lmat.m[13];
  81412. var lz = lmat.m[14];
  81413. var parent = this.getParent();
  81414. var parentScale = Bone._tmpMats[3];
  81415. var parentScaleInv = Bone._tmpMats[4];
  81416. if (parent && space == BABYLON.Space.WORLD) {
  81417. if (mesh) {
  81418. parentScale.copyFrom(mesh.getWorldMatrix());
  81419. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  81420. }
  81421. else {
  81422. parentScale.copyFrom(parent.getAbsoluteTransform());
  81423. }
  81424. parentScaleInv.copyFrom(parentScale);
  81425. parentScaleInv.invert();
  81426. lmat.multiplyToRef(parentScale, lmat);
  81427. lmat.multiplyToRef(rmat, lmat);
  81428. lmat.multiplyToRef(parentScaleInv, lmat);
  81429. }
  81430. else {
  81431. if (space == BABYLON.Space.WORLD && mesh) {
  81432. parentScale.copyFrom(mesh.getWorldMatrix());
  81433. parentScaleInv.copyFrom(parentScale);
  81434. parentScaleInv.invert();
  81435. lmat.multiplyToRef(parentScale, lmat);
  81436. lmat.multiplyToRef(rmat, lmat);
  81437. lmat.multiplyToRef(parentScaleInv, lmat);
  81438. }
  81439. else {
  81440. lmat.multiplyToRef(rmat, lmat);
  81441. }
  81442. }
  81443. lmat.m[12] = lx;
  81444. lmat.m[13] = ly;
  81445. lmat.m[14] = lz;
  81446. this.computeAbsoluteTransforms();
  81447. this._markAsDirtyAndDecompose();
  81448. };
  81449. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  81450. var scaleMatrix = Bone._tmpMats[2];
  81451. rotMatInv.copyFrom(this.getAbsoluteTransform());
  81452. if (mesh) {
  81453. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  81454. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  81455. }
  81456. rotMatInv.invert();
  81457. if (isNaN(rotMatInv.m[0])) {
  81458. // Matrix failed to invert.
  81459. // This can happen if scale is zero for example.
  81460. return false;
  81461. }
  81462. scaleMatrix.m[0] *= this._scalingDeterminant;
  81463. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  81464. return true;
  81465. };
  81466. /**
  81467. * Get the position of the bone in local or world space
  81468. * @param space The space that the returned position is in
  81469. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81470. * @returns The position of the bone
  81471. */
  81472. Bone.prototype.getPosition = function (space, mesh) {
  81473. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81474. if (mesh === void 0) { mesh = null; }
  81475. var pos = BABYLON.Vector3.Zero();
  81476. this.getPositionToRef(space, mesh, pos);
  81477. return pos;
  81478. };
  81479. /**
  81480. * Copy the position of the bone to a vector3 in local or world space
  81481. * @param space The space that the returned position is in
  81482. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81483. * @param result The vector3 to copy the position to
  81484. */
  81485. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  81486. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81487. if (space == BABYLON.Space.LOCAL) {
  81488. var lm = this.getLocalMatrix();
  81489. result.x = lm.m[12];
  81490. result.y = lm.m[13];
  81491. result.z = lm.m[14];
  81492. }
  81493. else {
  81494. var wm = null;
  81495. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81496. if (mesh) {
  81497. wm = mesh.getWorldMatrix();
  81498. }
  81499. this._skeleton.computeAbsoluteTransforms();
  81500. var tmat = Bone._tmpMats[0];
  81501. if (mesh && wm) {
  81502. tmat.copyFrom(this.getAbsoluteTransform());
  81503. tmat.multiplyToRef(wm, tmat);
  81504. }
  81505. else {
  81506. tmat = this.getAbsoluteTransform();
  81507. }
  81508. result.x = tmat.m[12];
  81509. result.y = tmat.m[13];
  81510. result.z = tmat.m[14];
  81511. }
  81512. };
  81513. /**
  81514. * Get the absolute position of the bone (world space)
  81515. * @param mesh The mesh that this bone is attached to
  81516. * @returns The absolute position of the bone
  81517. */
  81518. Bone.prototype.getAbsolutePosition = function (mesh) {
  81519. if (mesh === void 0) { mesh = null; }
  81520. var pos = BABYLON.Vector3.Zero();
  81521. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  81522. return pos;
  81523. };
  81524. /**
  81525. * Copy the absolute position of the bone (world space) to the result param
  81526. * @param mesh The mesh that this bone is attached to
  81527. * @param result The vector3 to copy the absolute position to
  81528. */
  81529. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  81530. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  81531. };
  81532. /**
  81533. * Compute the absolute transforms of this bone and its children
  81534. */
  81535. Bone.prototype.computeAbsoluteTransforms = function () {
  81536. this._compose();
  81537. if (this._parent) {
  81538. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81539. }
  81540. else {
  81541. this._absoluteTransform.copyFrom(this._localMatrix);
  81542. var poseMatrix = this._skeleton.getPoseMatrix();
  81543. if (poseMatrix) {
  81544. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  81545. }
  81546. }
  81547. var children = this.children;
  81548. var len = children.length;
  81549. for (var i = 0; i < len; i++) {
  81550. children[i].computeAbsoluteTransforms();
  81551. }
  81552. };
  81553. /**
  81554. * Get the world direction from an axis that is in the local space of the bone
  81555. * @param localAxis The local direction that is used to compute the world direction
  81556. * @param mesh The mesh that this bone is attached to
  81557. * @returns The world direction
  81558. */
  81559. Bone.prototype.getDirection = function (localAxis, mesh) {
  81560. if (mesh === void 0) { mesh = null; }
  81561. var result = BABYLON.Vector3.Zero();
  81562. this.getDirectionToRef(localAxis, mesh, result);
  81563. return result;
  81564. };
  81565. /**
  81566. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  81567. * @param localAxis The local direction that is used to compute the world direction
  81568. * @param mesh The mesh that this bone is attached to
  81569. * @param result The vector3 that the world direction will be copied to
  81570. */
  81571. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  81572. if (mesh === void 0) { mesh = null; }
  81573. var wm = null;
  81574. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81575. if (mesh) {
  81576. wm = mesh.getWorldMatrix();
  81577. }
  81578. this._skeleton.computeAbsoluteTransforms();
  81579. var mat = Bone._tmpMats[0];
  81580. mat.copyFrom(this.getAbsoluteTransform());
  81581. if (mesh && wm) {
  81582. mat.multiplyToRef(wm, mat);
  81583. }
  81584. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  81585. result.normalize();
  81586. };
  81587. /**
  81588. * Get the euler rotation of the bone in local or world space
  81589. * @param space The space that the rotation should be in
  81590. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81591. * @returns The euler rotation
  81592. */
  81593. Bone.prototype.getRotation = function (space, mesh) {
  81594. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81595. if (mesh === void 0) { mesh = null; }
  81596. var result = BABYLON.Vector3.Zero();
  81597. this.getRotationToRef(space, mesh, result);
  81598. return result;
  81599. };
  81600. /**
  81601. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  81602. * @param space The space that the rotation should be in
  81603. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81604. * @param result The vector3 that the rotation should be copied to
  81605. */
  81606. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  81607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81608. if (mesh === void 0) { mesh = null; }
  81609. var quat = Bone._tmpQuat;
  81610. this.getRotationQuaternionToRef(space, mesh, quat);
  81611. quat.toEulerAnglesToRef(result);
  81612. };
  81613. /**
  81614. * Get the quaternion rotation of the bone in either local or world space
  81615. * @param space The space that the rotation should be in
  81616. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81617. * @returns The quaternion rotation
  81618. */
  81619. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  81620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81621. if (mesh === void 0) { mesh = null; }
  81622. var result = BABYLON.Quaternion.Identity();
  81623. this.getRotationQuaternionToRef(space, mesh, result);
  81624. return result;
  81625. };
  81626. /**
  81627. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  81628. * @param space The space that the rotation should be in
  81629. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81630. * @param result The quaternion that the rotation should be copied to
  81631. */
  81632. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  81633. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81634. if (mesh === void 0) { mesh = null; }
  81635. if (space == BABYLON.Space.LOCAL) {
  81636. this._decompose();
  81637. result.copyFrom(this._localRotation);
  81638. }
  81639. else {
  81640. var mat = Bone._tmpMats[0];
  81641. var amat = this.getAbsoluteTransform();
  81642. if (mesh) {
  81643. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81644. }
  81645. else {
  81646. mat.copyFrom(amat);
  81647. }
  81648. mat.m[0] *= this._scalingDeterminant;
  81649. mat.m[1] *= this._scalingDeterminant;
  81650. mat.m[2] *= this._scalingDeterminant;
  81651. mat.decompose(undefined, result, undefined);
  81652. }
  81653. };
  81654. /**
  81655. * Get the rotation matrix of the bone in local or world space
  81656. * @param space The space that the rotation should be in
  81657. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81658. * @returns The rotation matrix
  81659. */
  81660. Bone.prototype.getRotationMatrix = function (space, mesh) {
  81661. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81662. var result = BABYLON.Matrix.Identity();
  81663. this.getRotationMatrixToRef(space, mesh, result);
  81664. return result;
  81665. };
  81666. /**
  81667. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  81668. * @param space The space that the rotation should be in
  81669. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81670. * @param result The quaternion that the rotation should be copied to
  81671. */
  81672. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  81673. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81674. if (space == BABYLON.Space.LOCAL) {
  81675. this.getLocalMatrix().getRotationMatrixToRef(result);
  81676. }
  81677. else {
  81678. var mat = Bone._tmpMats[0];
  81679. var amat = this.getAbsoluteTransform();
  81680. if (mesh) {
  81681. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81682. }
  81683. else {
  81684. mat.copyFrom(amat);
  81685. }
  81686. mat.m[0] *= this._scalingDeterminant;
  81687. mat.m[1] *= this._scalingDeterminant;
  81688. mat.m[2] *= this._scalingDeterminant;
  81689. mat.getRotationMatrixToRef(result);
  81690. }
  81691. };
  81692. /**
  81693. * Get the world position of a point that is in the local space of the bone
  81694. * @param position The local position
  81695. * @param mesh The mesh that this bone is attached to
  81696. * @returns The world position
  81697. */
  81698. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  81699. if (mesh === void 0) { mesh = null; }
  81700. var result = BABYLON.Vector3.Zero();
  81701. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  81702. return result;
  81703. };
  81704. /**
  81705. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  81706. * @param position The local position
  81707. * @param mesh The mesh that this bone is attached to
  81708. * @param result The vector3 that the world position should be copied to
  81709. */
  81710. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  81711. if (mesh === void 0) { mesh = null; }
  81712. var wm = null;
  81713. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81714. if (mesh) {
  81715. wm = mesh.getWorldMatrix();
  81716. }
  81717. this._skeleton.computeAbsoluteTransforms();
  81718. var tmat = Bone._tmpMats[0];
  81719. if (mesh && wm) {
  81720. tmat.copyFrom(this.getAbsoluteTransform());
  81721. tmat.multiplyToRef(wm, tmat);
  81722. }
  81723. else {
  81724. tmat = this.getAbsoluteTransform();
  81725. }
  81726. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81727. };
  81728. /**
  81729. * Get the local position of a point that is in world space
  81730. * @param position The world position
  81731. * @param mesh The mesh that this bone is attached to
  81732. * @returns The local position
  81733. */
  81734. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  81735. if (mesh === void 0) { mesh = null; }
  81736. var result = BABYLON.Vector3.Zero();
  81737. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  81738. return result;
  81739. };
  81740. /**
  81741. * Get the local position of a point that is in world space and copy it to the result param
  81742. * @param position The world position
  81743. * @param mesh The mesh that this bone is attached to
  81744. * @param result The vector3 that the local position should be copied to
  81745. */
  81746. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  81747. if (mesh === void 0) { mesh = null; }
  81748. var wm = null;
  81749. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81750. if (mesh) {
  81751. wm = mesh.getWorldMatrix();
  81752. }
  81753. this._skeleton.computeAbsoluteTransforms();
  81754. var tmat = Bone._tmpMats[0];
  81755. tmat.copyFrom(this.getAbsoluteTransform());
  81756. if (mesh && wm) {
  81757. tmat.multiplyToRef(wm, tmat);
  81758. }
  81759. tmat.invert();
  81760. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81761. };
  81762. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81763. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  81764. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81765. return Bone;
  81766. }(BABYLON.Node));
  81767. BABYLON.Bone = Bone;
  81768. })(BABYLON || (BABYLON = {}));
  81769. //# sourceMappingURL=babylon.bone.js.map
  81770. var BABYLON;
  81771. (function (BABYLON) {
  81772. /**
  81773. * Class used to apply inverse kinematics to bones
  81774. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  81775. */
  81776. var BoneIKController = /** @class */ (function () {
  81777. /**
  81778. * Creates a new BoneIKController
  81779. * @param mesh defines the mesh to control
  81780. * @param bone defines the bone to control
  81781. * @param options defines options to set up the controller
  81782. */
  81783. function BoneIKController(mesh, bone, options) {
  81784. /**
  81785. * Gets or sets the target position
  81786. */
  81787. this.targetPosition = BABYLON.Vector3.Zero();
  81788. /**
  81789. * Gets or sets the pole target position
  81790. */
  81791. this.poleTargetPosition = BABYLON.Vector3.Zero();
  81792. /**
  81793. * Gets or sets the pole target local offset
  81794. */
  81795. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  81796. /**
  81797. * Gets or sets the pole angle
  81798. */
  81799. this.poleAngle = 0;
  81800. /**
  81801. * 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)
  81802. */
  81803. this.slerpAmount = 1;
  81804. this._bone1Quat = BABYLON.Quaternion.Identity();
  81805. this._bone1Mat = BABYLON.Matrix.Identity();
  81806. this._bone2Ang = Math.PI;
  81807. this._maxAngle = Math.PI;
  81808. this._rightHandedSystem = false;
  81809. this._bendAxis = BABYLON.Vector3.Right();
  81810. this._slerping = false;
  81811. this._adjustRoll = 0;
  81812. this._bone2 = bone;
  81813. this._bone1 = bone.getParent();
  81814. if (!this._bone1) {
  81815. return;
  81816. }
  81817. this.mesh = mesh;
  81818. var bonePos = bone.getPosition();
  81819. if (bone.getAbsoluteTransform().determinant() > 0) {
  81820. this._rightHandedSystem = true;
  81821. this._bendAxis.x = 0;
  81822. this._bendAxis.y = 0;
  81823. this._bendAxis.z = -1;
  81824. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  81825. this._adjustRoll = Math.PI * .5;
  81826. this._bendAxis.z = 1;
  81827. }
  81828. }
  81829. if (this._bone1.length) {
  81830. var boneScale1 = this._bone1.getScale();
  81831. var boneScale2 = this._bone2.getScale();
  81832. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  81833. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  81834. }
  81835. else if (this._bone1.children[0]) {
  81836. mesh.computeWorldMatrix(true);
  81837. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  81838. var pos2 = this._bone2.getAbsolutePosition(mesh);
  81839. var pos3 = this._bone1.getAbsolutePosition(mesh);
  81840. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  81841. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  81842. }
  81843. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  81844. this.maxAngle = Math.PI;
  81845. if (options) {
  81846. if (options.targetMesh) {
  81847. this.targetMesh = options.targetMesh;
  81848. this.targetMesh.computeWorldMatrix(true);
  81849. }
  81850. if (options.poleTargetMesh) {
  81851. this.poleTargetMesh = options.poleTargetMesh;
  81852. this.poleTargetMesh.computeWorldMatrix(true);
  81853. }
  81854. else if (options.poleTargetBone) {
  81855. this.poleTargetBone = options.poleTargetBone;
  81856. }
  81857. else if (this._bone1.getParent()) {
  81858. this.poleTargetBone = this._bone1.getParent();
  81859. }
  81860. if (options.poleTargetLocalOffset) {
  81861. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  81862. }
  81863. if (options.poleAngle) {
  81864. this.poleAngle = options.poleAngle;
  81865. }
  81866. if (options.bendAxis) {
  81867. this._bendAxis.copyFrom(options.bendAxis);
  81868. }
  81869. if (options.maxAngle) {
  81870. this.maxAngle = options.maxAngle;
  81871. }
  81872. if (options.slerpAmount) {
  81873. this.slerpAmount = options.slerpAmount;
  81874. }
  81875. }
  81876. }
  81877. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  81878. /**
  81879. * Gets or sets maximum allowed angle
  81880. */
  81881. get: function () {
  81882. return this._maxAngle;
  81883. },
  81884. set: function (value) {
  81885. this._setMaxAngle(value);
  81886. },
  81887. enumerable: true,
  81888. configurable: true
  81889. });
  81890. BoneIKController.prototype._setMaxAngle = function (ang) {
  81891. if (ang < 0) {
  81892. ang = 0;
  81893. }
  81894. if (ang > Math.PI || ang == undefined) {
  81895. ang = Math.PI;
  81896. }
  81897. this._maxAngle = ang;
  81898. var a = this._bone1Length;
  81899. var b = this._bone2Length;
  81900. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  81901. };
  81902. /**
  81903. * Force the controller to update the bones
  81904. */
  81905. BoneIKController.prototype.update = function () {
  81906. var bone1 = this._bone1;
  81907. if (!bone1) {
  81908. return;
  81909. }
  81910. var target = this.targetPosition;
  81911. var poleTarget = this.poleTargetPosition;
  81912. var mat1 = BoneIKController._tmpMats[0];
  81913. var mat2 = BoneIKController._tmpMats[1];
  81914. if (this.targetMesh) {
  81915. target.copyFrom(this.targetMesh.getAbsolutePosition());
  81916. }
  81917. if (this.poleTargetBone) {
  81918. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  81919. }
  81920. else if (this.poleTargetMesh) {
  81921. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  81922. }
  81923. var bonePos = BoneIKController._tmpVecs[0];
  81924. var zaxis = BoneIKController._tmpVecs[1];
  81925. var xaxis = BoneIKController._tmpVecs[2];
  81926. var yaxis = BoneIKController._tmpVecs[3];
  81927. var upAxis = BoneIKController._tmpVecs[4];
  81928. var _tmpQuat = BoneIKController._tmpQuat;
  81929. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  81930. poleTarget.subtractToRef(bonePos, upAxis);
  81931. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  81932. upAxis.y = 1;
  81933. }
  81934. else {
  81935. upAxis.normalize();
  81936. }
  81937. target.subtractToRef(bonePos, yaxis);
  81938. yaxis.normalize();
  81939. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  81940. zaxis.normalize();
  81941. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  81942. xaxis.normalize();
  81943. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  81944. var a = this._bone1Length;
  81945. var b = this._bone2Length;
  81946. var c = BABYLON.Vector3.Distance(bonePos, target);
  81947. if (this._maxReach > 0) {
  81948. c = Math.min(this._maxReach, c);
  81949. }
  81950. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  81951. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  81952. if (acosa > 1) {
  81953. acosa = 1;
  81954. }
  81955. if (acosb > 1) {
  81956. acosb = 1;
  81957. }
  81958. if (acosa < -1) {
  81959. acosa = -1;
  81960. }
  81961. if (acosb < -1) {
  81962. acosb = -1;
  81963. }
  81964. var angA = Math.acos(acosa);
  81965. var angB = Math.acos(acosb);
  81966. var angC = -angA - angB;
  81967. if (this._rightHandedSystem) {
  81968. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  81969. mat2.multiplyToRef(mat1, mat1);
  81970. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  81971. mat2.multiplyToRef(mat1, mat1);
  81972. }
  81973. else {
  81974. var _tmpVec = BoneIKController._tmpVecs[5];
  81975. _tmpVec.copyFrom(this._bendAxis);
  81976. _tmpVec.x *= -1;
  81977. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  81978. mat2.multiplyToRef(mat1, mat1);
  81979. }
  81980. if (this.poleAngle) {
  81981. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  81982. mat1.multiplyToRef(mat2, mat1);
  81983. }
  81984. if (this._bone1) {
  81985. if (this.slerpAmount < 1) {
  81986. if (!this._slerping) {
  81987. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  81988. }
  81989. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  81990. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  81991. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  81992. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  81993. this._slerping = true;
  81994. }
  81995. else {
  81996. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  81997. this._bone1Mat.copyFrom(mat1);
  81998. this._slerping = false;
  81999. }
  82000. }
  82001. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  82002. this._bone2Ang = angC;
  82003. };
  82004. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82005. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  82006. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82007. return BoneIKController;
  82008. }());
  82009. BABYLON.BoneIKController = BoneIKController;
  82010. })(BABYLON || (BABYLON = {}));
  82011. //# sourceMappingURL=babylon.boneIKController.js.map
  82012. var BABYLON;
  82013. (function (BABYLON) {
  82014. /**
  82015. * Class used to make a bone look toward a point in space
  82016. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  82017. */
  82018. var BoneLookController = /** @class */ (function () {
  82019. /**
  82020. * Create a BoneLookController
  82021. * @param mesh the mesh that the bone belongs to
  82022. * @param bone the bone that will be looking to the target
  82023. * @param target the target Vector3 to look at
  82024. * @param settings optional settings:
  82025. * * maxYaw: the maximum angle the bone will yaw to
  82026. * * minYaw: the minimum angle the bone will yaw to
  82027. * * maxPitch: the maximum angle the bone will pitch to
  82028. * * minPitch: the minimum angle the bone will yaw to
  82029. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  82030. * * upAxis: the up axis of the coordinate system
  82031. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  82032. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  82033. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  82034. * * adjustYaw: used to make an adjustment to the yaw of the bone
  82035. * * adjustPitch: used to make an adjustment to the pitch of the bone
  82036. * * adjustRoll: used to make an adjustment to the roll of the bone
  82037. **/
  82038. function BoneLookController(mesh, bone, target, options) {
  82039. /**
  82040. * The up axis of the coordinate system that is used when the bone is rotated
  82041. */
  82042. this.upAxis = BABYLON.Vector3.Up();
  82043. /**
  82044. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  82045. */
  82046. this.upAxisSpace = BABYLON.Space.LOCAL;
  82047. /**
  82048. * Used to make an adjustment to the yaw of the bone
  82049. */
  82050. this.adjustYaw = 0;
  82051. /**
  82052. * Used to make an adjustment to the pitch of the bone
  82053. */
  82054. this.adjustPitch = 0;
  82055. /**
  82056. * Used to make an adjustment to the roll of the bone
  82057. */
  82058. this.adjustRoll = 0;
  82059. /**
  82060. * 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)
  82061. */
  82062. this.slerpAmount = 1;
  82063. this._boneQuat = BABYLON.Quaternion.Identity();
  82064. this._slerping = false;
  82065. this._firstFrameSkipped = false;
  82066. this._fowardAxis = BABYLON.Vector3.Forward();
  82067. this.mesh = mesh;
  82068. this.bone = bone;
  82069. this.target = target;
  82070. if (options) {
  82071. if (options.adjustYaw) {
  82072. this.adjustYaw = options.adjustYaw;
  82073. }
  82074. if (options.adjustPitch) {
  82075. this.adjustPitch = options.adjustPitch;
  82076. }
  82077. if (options.adjustRoll) {
  82078. this.adjustRoll = options.adjustRoll;
  82079. }
  82080. if (options.maxYaw != null) {
  82081. this.maxYaw = options.maxYaw;
  82082. }
  82083. else {
  82084. this.maxYaw = Math.PI;
  82085. }
  82086. if (options.minYaw != null) {
  82087. this.minYaw = options.minYaw;
  82088. }
  82089. else {
  82090. this.minYaw = -Math.PI;
  82091. }
  82092. if (options.maxPitch != null) {
  82093. this.maxPitch = options.maxPitch;
  82094. }
  82095. else {
  82096. this.maxPitch = Math.PI;
  82097. }
  82098. if (options.minPitch != null) {
  82099. this.minPitch = options.minPitch;
  82100. }
  82101. else {
  82102. this.minPitch = -Math.PI;
  82103. }
  82104. if (options.slerpAmount != null) {
  82105. this.slerpAmount = options.slerpAmount;
  82106. }
  82107. if (options.upAxis != null) {
  82108. this.upAxis = options.upAxis;
  82109. }
  82110. if (options.upAxisSpace != null) {
  82111. this.upAxisSpace = options.upAxisSpace;
  82112. }
  82113. if (options.yawAxis != null || options.pitchAxis != null) {
  82114. var newYawAxis = BABYLON.Axis.Y;
  82115. var newPitchAxis = BABYLON.Axis.X;
  82116. if (options.yawAxis != null) {
  82117. newYawAxis = options.yawAxis.clone();
  82118. newYawAxis.normalize();
  82119. }
  82120. if (options.pitchAxis != null) {
  82121. newPitchAxis = options.pitchAxis.clone();
  82122. newPitchAxis.normalize();
  82123. }
  82124. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  82125. this._transformYawPitch = BABYLON.Matrix.Identity();
  82126. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  82127. this._transformYawPitchInv = this._transformYawPitch.clone();
  82128. this._transformYawPitch.invert();
  82129. }
  82130. }
  82131. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  82132. this.upAxisSpace = BABYLON.Space.LOCAL;
  82133. }
  82134. }
  82135. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  82136. /**
  82137. * Gets or sets the minimum yaw angle that the bone can look to
  82138. */
  82139. get: function () {
  82140. return this._minYaw;
  82141. },
  82142. set: function (value) {
  82143. this._minYaw = value;
  82144. this._minYawSin = Math.sin(value);
  82145. this._minYawCos = Math.cos(value);
  82146. if (this._maxYaw != null) {
  82147. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82148. this._yawRange = this._maxYaw - this._minYaw;
  82149. }
  82150. },
  82151. enumerable: true,
  82152. configurable: true
  82153. });
  82154. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  82155. /**
  82156. * Gets or sets the maximum yaw angle that the bone can look to
  82157. */
  82158. get: function () {
  82159. return this._maxYaw;
  82160. },
  82161. set: function (value) {
  82162. this._maxYaw = value;
  82163. this._maxYawSin = Math.sin(value);
  82164. this._maxYawCos = Math.cos(value);
  82165. if (this._minYaw != null) {
  82166. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82167. this._yawRange = this._maxYaw - this._minYaw;
  82168. }
  82169. },
  82170. enumerable: true,
  82171. configurable: true
  82172. });
  82173. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  82174. /**
  82175. * Gets or sets the minimum pitch angle that the bone can look to
  82176. */
  82177. get: function () {
  82178. return this._minPitch;
  82179. },
  82180. set: function (value) {
  82181. this._minPitch = value;
  82182. this._minPitchTan = Math.tan(value);
  82183. },
  82184. enumerable: true,
  82185. configurable: true
  82186. });
  82187. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  82188. /**
  82189. * Gets or sets the maximum pitch angle that the bone can look to
  82190. */
  82191. get: function () {
  82192. return this._maxPitch;
  82193. },
  82194. set: function (value) {
  82195. this._maxPitch = value;
  82196. this._maxPitchTan = Math.tan(value);
  82197. },
  82198. enumerable: true,
  82199. configurable: true
  82200. });
  82201. /**
  82202. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  82203. */
  82204. BoneLookController.prototype.update = function () {
  82205. //skip the first frame when slerping so that the mesh rotation is correct
  82206. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  82207. this._firstFrameSkipped = true;
  82208. return;
  82209. }
  82210. var bone = this.bone;
  82211. var bonePos = BoneLookController._tmpVecs[0];
  82212. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  82213. var target = this.target;
  82214. var _tmpMat1 = BoneLookController._tmpMats[0];
  82215. var _tmpMat2 = BoneLookController._tmpMats[1];
  82216. var mesh = this.mesh;
  82217. var parentBone = bone.getParent();
  82218. var upAxis = BoneLookController._tmpVecs[1];
  82219. upAxis.copyFrom(this.upAxis);
  82220. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  82221. if (this._transformYawPitch) {
  82222. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  82223. }
  82224. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  82225. }
  82226. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  82227. mesh.getDirectionToRef(upAxis, upAxis);
  82228. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  82229. upAxis.normalize();
  82230. }
  82231. }
  82232. var checkYaw = false;
  82233. var checkPitch = false;
  82234. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  82235. checkYaw = true;
  82236. }
  82237. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  82238. checkPitch = true;
  82239. }
  82240. if (checkYaw || checkPitch) {
  82241. var spaceMat = BoneLookController._tmpMats[2];
  82242. var spaceMatInv = BoneLookController._tmpMats[3];
  82243. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  82244. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  82245. }
  82246. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  82247. spaceMat.copyFrom(mesh.getWorldMatrix());
  82248. }
  82249. else {
  82250. var forwardAxis = BoneLookController._tmpVecs[2];
  82251. forwardAxis.copyFrom(this._fowardAxis);
  82252. if (this._transformYawPitch) {
  82253. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  82254. }
  82255. if (parentBone) {
  82256. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  82257. }
  82258. else {
  82259. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  82260. }
  82261. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  82262. rightAxis.normalize();
  82263. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  82264. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  82265. }
  82266. spaceMat.invertToRef(spaceMatInv);
  82267. var xzlen = null;
  82268. if (checkPitch) {
  82269. var localTarget = BoneLookController._tmpVecs[3];
  82270. target.subtractToRef(bonePos, localTarget);
  82271. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82272. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82273. var pitch = Math.atan2(localTarget.y, xzlen);
  82274. var newPitch = pitch;
  82275. if (pitch > this._maxPitch) {
  82276. localTarget.y = this._maxPitchTan * xzlen;
  82277. newPitch = this._maxPitch;
  82278. }
  82279. else if (pitch < this._minPitch) {
  82280. localTarget.y = this._minPitchTan * xzlen;
  82281. newPitch = this._minPitch;
  82282. }
  82283. if (pitch != newPitch) {
  82284. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82285. localTarget.addInPlace(bonePos);
  82286. target = localTarget;
  82287. }
  82288. }
  82289. if (checkYaw) {
  82290. var localTarget = BoneLookController._tmpVecs[4];
  82291. target.subtractToRef(bonePos, localTarget);
  82292. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82293. var yaw = Math.atan2(localTarget.x, localTarget.z);
  82294. var newYaw = yaw;
  82295. if (yaw > this._maxYaw || yaw < this._minYaw) {
  82296. if (xzlen == null) {
  82297. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82298. }
  82299. if (this._yawRange > Math.PI) {
  82300. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  82301. localTarget.z = this._maxYawCos * xzlen;
  82302. localTarget.x = this._maxYawSin * xzlen;
  82303. newYaw = this._maxYaw;
  82304. }
  82305. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  82306. localTarget.z = this._minYawCos * xzlen;
  82307. localTarget.x = this._minYawSin * xzlen;
  82308. newYaw = this._minYaw;
  82309. }
  82310. }
  82311. else {
  82312. if (yaw > this._maxYaw) {
  82313. localTarget.z = this._maxYawCos * xzlen;
  82314. localTarget.x = this._maxYawSin * xzlen;
  82315. newYaw = this._maxYaw;
  82316. }
  82317. else if (yaw < this._minYaw) {
  82318. localTarget.z = this._minYawCos * xzlen;
  82319. localTarget.x = this._minYawSin * xzlen;
  82320. newYaw = this._minYaw;
  82321. }
  82322. }
  82323. }
  82324. if (this._slerping && this._yawRange > Math.PI) {
  82325. //are we going to be crossing into the min/max region?
  82326. var boneFwd = BoneLookController._tmpVecs[8];
  82327. boneFwd.copyFrom(BABYLON.Axis.Z);
  82328. if (this._transformYawPitch) {
  82329. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  82330. }
  82331. var boneRotMat = BoneLookController._tmpMats[4];
  82332. this._boneQuat.toRotationMatrix(boneRotMat);
  82333. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  82334. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  82335. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  82336. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  82337. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  82338. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  82339. if (angBtwTar > angBtwMidYaw) {
  82340. if (xzlen == null) {
  82341. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82342. }
  82343. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  82344. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  82345. if (angBtwMin < angBtwMax) {
  82346. newYaw = boneYaw + Math.PI * .75;
  82347. localTarget.z = Math.cos(newYaw) * xzlen;
  82348. localTarget.x = Math.sin(newYaw) * xzlen;
  82349. }
  82350. else {
  82351. newYaw = boneYaw - Math.PI * .75;
  82352. localTarget.z = Math.cos(newYaw) * xzlen;
  82353. localTarget.x = Math.sin(newYaw) * xzlen;
  82354. }
  82355. }
  82356. }
  82357. if (yaw != newYaw) {
  82358. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82359. localTarget.addInPlace(bonePos);
  82360. target = localTarget;
  82361. }
  82362. }
  82363. }
  82364. var zaxis = BoneLookController._tmpVecs[5];
  82365. var xaxis = BoneLookController._tmpVecs[6];
  82366. var yaxis = BoneLookController._tmpVecs[7];
  82367. var _tmpQuat = BoneLookController._tmpQuat;
  82368. target.subtractToRef(bonePos, zaxis);
  82369. zaxis.normalize();
  82370. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  82371. xaxis.normalize();
  82372. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  82373. yaxis.normalize();
  82374. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  82375. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  82376. return;
  82377. }
  82378. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  82379. return;
  82380. }
  82381. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  82382. return;
  82383. }
  82384. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  82385. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  82386. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  82387. }
  82388. if (this.slerpAmount < 1) {
  82389. if (!this._slerping) {
  82390. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  82391. }
  82392. if (this._transformYawPitch) {
  82393. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82394. }
  82395. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  82396. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  82397. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  82398. this._slerping = true;
  82399. }
  82400. else {
  82401. if (this._transformYawPitch) {
  82402. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82403. }
  82404. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  82405. this._slerping = false;
  82406. }
  82407. };
  82408. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  82409. var angDiff = ang2 - ang1;
  82410. angDiff %= Math.PI * 2;
  82411. if (angDiff > Math.PI) {
  82412. angDiff -= Math.PI * 2;
  82413. }
  82414. else if (angDiff < -Math.PI) {
  82415. angDiff += Math.PI * 2;
  82416. }
  82417. return angDiff;
  82418. };
  82419. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  82420. ang1 %= (2 * Math.PI);
  82421. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82422. ang2 %= (2 * Math.PI);
  82423. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82424. var ab = 0;
  82425. if (ang1 < ang2) {
  82426. ab = ang2 - ang1;
  82427. }
  82428. else {
  82429. ab = ang1 - ang2;
  82430. }
  82431. if (ab > Math.PI) {
  82432. ab = Math.PI * 2 - ab;
  82433. }
  82434. return ab;
  82435. };
  82436. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  82437. ang %= (2 * Math.PI);
  82438. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  82439. ang1 %= (2 * Math.PI);
  82440. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82441. ang2 %= (2 * Math.PI);
  82442. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82443. if (ang1 < ang2) {
  82444. if (ang > ang1 && ang < ang2) {
  82445. return true;
  82446. }
  82447. }
  82448. else {
  82449. if (ang > ang2 && ang < ang1) {
  82450. return true;
  82451. }
  82452. }
  82453. return false;
  82454. };
  82455. 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()];
  82456. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  82457. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82458. return BoneLookController;
  82459. }());
  82460. BABYLON.BoneLookController = BoneLookController;
  82461. })(BABYLON || (BABYLON = {}));
  82462. //# sourceMappingURL=babylon.boneLookController.js.map
  82463. var BABYLON;
  82464. (function (BABYLON) {
  82465. /**
  82466. * Class used to handle skinning animations
  82467. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82468. */
  82469. var Skeleton = /** @class */ (function () {
  82470. /**
  82471. * Creates a new skeleton
  82472. * @param name defines the skeleton name
  82473. * @param id defines the skeleton Id
  82474. * @param scene defines the hosting scene
  82475. */
  82476. function Skeleton(
  82477. /** defines the skeleton name */
  82478. name,
  82479. /** defines the skeleton Id */
  82480. id, scene) {
  82481. this.name = name;
  82482. this.id = id;
  82483. /**
  82484. * Gets the list of child bones
  82485. */
  82486. this.bones = new Array();
  82487. /**
  82488. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  82489. */
  82490. this.needInitialSkinMatrix = false;
  82491. this._isDirty = true;
  82492. this._meshesWithPoseMatrix = new Array();
  82493. this._identity = BABYLON.Matrix.Identity();
  82494. this._ranges = {};
  82495. this._lastAbsoluteTransformsUpdateId = -1;
  82496. /**
  82497. * Specifies if the skeleton should be serialized
  82498. */
  82499. this.doNotSerialize = false;
  82500. this._animationPropertiesOverride = null;
  82501. // Events
  82502. /**
  82503. * An observable triggered before computing the skeleton's matrices
  82504. */
  82505. this.onBeforeComputeObservable = new BABYLON.Observable();
  82506. this.bones = [];
  82507. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82508. scene.skeletons.push(this);
  82509. //make sure it will recalculate the matrix next time prepare is called.
  82510. this._isDirty = true;
  82511. }
  82512. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  82513. /**
  82514. * Gets or sets the animation properties override
  82515. */
  82516. get: function () {
  82517. if (!this._animationPropertiesOverride) {
  82518. return this._scene.animationPropertiesOverride;
  82519. }
  82520. return this._animationPropertiesOverride;
  82521. },
  82522. set: function (value) {
  82523. this._animationPropertiesOverride = value;
  82524. },
  82525. enumerable: true,
  82526. configurable: true
  82527. });
  82528. // Members
  82529. /**
  82530. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  82531. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  82532. * @returns a Float32Array containing matrices data
  82533. */
  82534. Skeleton.prototype.getTransformMatrices = function (mesh) {
  82535. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  82536. return mesh._bonesTransformMatrices;
  82537. }
  82538. if (!this._transformMatrices) {
  82539. this.prepare();
  82540. }
  82541. return this._transformMatrices;
  82542. };
  82543. /**
  82544. * Gets the current hosting scene
  82545. * @returns a scene object
  82546. */
  82547. Skeleton.prototype.getScene = function () {
  82548. return this._scene;
  82549. };
  82550. // Methods
  82551. /**
  82552. * Gets a string representing the current skeleton data
  82553. * @param fullDetails defines a boolean indicating if we want a verbose version
  82554. * @returns a string representing the current skeleton data
  82555. */
  82556. Skeleton.prototype.toString = function (fullDetails) {
  82557. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  82558. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  82559. if (fullDetails) {
  82560. ret += ", Ranges: {";
  82561. var first = true;
  82562. for (var name_1 in this._ranges) {
  82563. if (first) {
  82564. ret += ", ";
  82565. first = false;
  82566. }
  82567. ret += name_1;
  82568. }
  82569. ret += "}";
  82570. }
  82571. return ret;
  82572. };
  82573. /**
  82574. * Get bone's index searching by name
  82575. * @param name defines bone's name to search for
  82576. * @return the indice of the bone. Returns -1 if not found
  82577. */
  82578. Skeleton.prototype.getBoneIndexByName = function (name) {
  82579. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  82580. if (this.bones[boneIndex].name === name) {
  82581. return boneIndex;
  82582. }
  82583. }
  82584. return -1;
  82585. };
  82586. /**
  82587. * Creater a new animation range
  82588. * @param name defines the name of the range
  82589. * @param from defines the start key
  82590. * @param to defines the end key
  82591. */
  82592. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  82593. // check name not already in use
  82594. if (!this._ranges[name]) {
  82595. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  82596. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82597. if (this.bones[i].animations[0]) {
  82598. this.bones[i].animations[0].createRange(name, from, to);
  82599. }
  82600. }
  82601. }
  82602. };
  82603. /**
  82604. * Delete a specific animation range
  82605. * @param name defines the name of the range
  82606. * @param deleteFrames defines if frames must be removed as well
  82607. */
  82608. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  82609. if (deleteFrames === void 0) { deleteFrames = true; }
  82610. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82611. if (this.bones[i].animations[0]) {
  82612. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  82613. }
  82614. }
  82615. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  82616. };
  82617. /**
  82618. * Gets a specific animation range
  82619. * @param name defines the name of the range to look for
  82620. * @returns the requested animation range or null if not found
  82621. */
  82622. Skeleton.prototype.getAnimationRange = function (name) {
  82623. return this._ranges[name];
  82624. };
  82625. /**
  82626. * Gets the list of all animation ranges defined on this skeleton
  82627. * @returns an array
  82628. */
  82629. Skeleton.prototype.getAnimationRanges = function () {
  82630. var animationRanges = [];
  82631. var name;
  82632. var i = 0;
  82633. for (name in this._ranges) {
  82634. animationRanges[i] = this._ranges[name];
  82635. i++;
  82636. }
  82637. return animationRanges;
  82638. };
  82639. /**
  82640. * Copy animation range from a source skeleton.
  82641. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  82642. * @param source defines the source skeleton
  82643. * @param name defines the name of the range to copy
  82644. * @param rescaleAsRequired defines if rescaling must be applied if required
  82645. * @returns true if operation was successful
  82646. */
  82647. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  82648. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82649. if (this._ranges[name] || !source.getAnimationRange(name)) {
  82650. return false;
  82651. }
  82652. var ret = true;
  82653. var frameOffset = this._getHighestAnimationFrame() + 1;
  82654. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  82655. var boneDict = {};
  82656. var sourceBones = source.bones;
  82657. var nBones;
  82658. var i;
  82659. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  82660. boneDict[sourceBones[i].name] = sourceBones[i];
  82661. }
  82662. if (this.bones.length !== sourceBones.length) {
  82663. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  82664. ret = false;
  82665. }
  82666. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  82667. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  82668. var boneName = this.bones[i].name;
  82669. var sourceBone = boneDict[boneName];
  82670. if (sourceBone) {
  82671. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  82672. }
  82673. else {
  82674. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  82675. ret = false;
  82676. }
  82677. }
  82678. // do not call createAnimationRange(), since it also is done to bones, which was already done
  82679. var range = source.getAnimationRange(name);
  82680. if (range) {
  82681. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  82682. }
  82683. return ret;
  82684. };
  82685. /**
  82686. * Forces the skeleton to go to rest pose
  82687. */
  82688. Skeleton.prototype.returnToRest = function () {
  82689. for (var index = 0; index < this.bones.length; index++) {
  82690. this.bones[index].returnToRest();
  82691. }
  82692. };
  82693. Skeleton.prototype._getHighestAnimationFrame = function () {
  82694. var ret = 0;
  82695. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82696. if (this.bones[i].animations[0]) {
  82697. var highest = this.bones[i].animations[0].getHighestFrame();
  82698. if (ret < highest) {
  82699. ret = highest;
  82700. }
  82701. }
  82702. }
  82703. return ret;
  82704. };
  82705. /**
  82706. * Begin a specific animation range
  82707. * @param name defines the name of the range to start
  82708. * @param loop defines if looping must be turned on (false by default)
  82709. * @param speedRatio defines the speed ratio to apply (1 by default)
  82710. * @param onAnimationEnd defines a callback which will be called when animation will end
  82711. * @returns a new animatable
  82712. */
  82713. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  82714. var range = this.getAnimationRange(name);
  82715. if (!range) {
  82716. return null;
  82717. }
  82718. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  82719. };
  82720. /** @hidden */
  82721. Skeleton.prototype._markAsDirty = function () {
  82722. this._isDirty = true;
  82723. };
  82724. /** @hidden */
  82725. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  82726. this._meshesWithPoseMatrix.push(mesh);
  82727. };
  82728. /** @hidden */
  82729. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  82730. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  82731. if (index > -1) {
  82732. this._meshesWithPoseMatrix.splice(index, 1);
  82733. }
  82734. };
  82735. /** @hidden */
  82736. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  82737. this.onBeforeComputeObservable.notifyObservers(this);
  82738. for (var index = 0; index < this.bones.length; index++) {
  82739. var bone = this.bones[index];
  82740. var parentBone = bone.getParent();
  82741. if (parentBone) {
  82742. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  82743. }
  82744. else {
  82745. if (initialSkinMatrix) {
  82746. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  82747. }
  82748. else {
  82749. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  82750. }
  82751. }
  82752. if (bone._index !== -1) {
  82753. var mappedIndex = bone._index === null ? index : bone._index;
  82754. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  82755. }
  82756. }
  82757. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  82758. };
  82759. /**
  82760. * Build all resources required to render a skeleton
  82761. */
  82762. Skeleton.prototype.prepare = function () {
  82763. if (!this._isDirty) {
  82764. return;
  82765. }
  82766. if (this.needInitialSkinMatrix) {
  82767. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  82768. var mesh = this._meshesWithPoseMatrix[index];
  82769. var poseMatrix = mesh.getPoseMatrix();
  82770. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  82771. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82772. }
  82773. if (this._synchronizedWithMesh !== mesh) {
  82774. this._synchronizedWithMesh = mesh;
  82775. // Prepare bones
  82776. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  82777. var bone = this.bones[boneIndex];
  82778. if (!bone.getParent()) {
  82779. var matrix = bone.getBaseMatrix();
  82780. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  82781. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  82782. }
  82783. }
  82784. }
  82785. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  82786. }
  82787. }
  82788. else {
  82789. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  82790. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82791. }
  82792. this._computeTransformMatrices(this._transformMatrices, null);
  82793. }
  82794. this._isDirty = false;
  82795. this._scene._activeBones.addCount(this.bones.length, false);
  82796. };
  82797. /**
  82798. * Gets the list of animatables currently running for this skeleton
  82799. * @returns an array of animatables
  82800. */
  82801. Skeleton.prototype.getAnimatables = function () {
  82802. if (!this._animatables || this._animatables.length !== this.bones.length) {
  82803. this._animatables = [];
  82804. for (var index = 0; index < this.bones.length; index++) {
  82805. this._animatables.push(this.bones[index]);
  82806. }
  82807. }
  82808. return this._animatables;
  82809. };
  82810. /**
  82811. * Clone the current skeleton
  82812. * @param name defines the name of the new skeleton
  82813. * @param id defines the id of the enw skeleton
  82814. * @returns the new skeleton
  82815. */
  82816. Skeleton.prototype.clone = function (name, id) {
  82817. var result = new Skeleton(name, id || name, this._scene);
  82818. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82819. for (var index = 0; index < this.bones.length; index++) {
  82820. var source = this.bones[index];
  82821. var parentBone = null;
  82822. var parent_1 = source.getParent();
  82823. if (parent_1) {
  82824. var parentIndex = this.bones.indexOf(parent_1);
  82825. parentBone = result.bones[parentIndex];
  82826. }
  82827. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  82828. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  82829. }
  82830. if (this._ranges) {
  82831. result._ranges = {};
  82832. for (var rangeName in this._ranges) {
  82833. var range = this._ranges[rangeName];
  82834. if (range) {
  82835. result._ranges[rangeName] = range.clone();
  82836. }
  82837. }
  82838. }
  82839. this._isDirty = true;
  82840. return result;
  82841. };
  82842. /**
  82843. * Enable animation blending for this skeleton
  82844. * @param blendingSpeed defines the blending speed to apply
  82845. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  82846. */
  82847. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  82848. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  82849. this.bones.forEach(function (bone) {
  82850. bone.animations.forEach(function (animation) {
  82851. animation.enableBlending = true;
  82852. animation.blendingSpeed = blendingSpeed;
  82853. });
  82854. });
  82855. };
  82856. /**
  82857. * Releases all resources associated with the current skeleton
  82858. */
  82859. Skeleton.prototype.dispose = function () {
  82860. this._meshesWithPoseMatrix = [];
  82861. // Animations
  82862. this.getScene().stopAnimation(this);
  82863. // Remove from scene
  82864. this.getScene().removeSkeleton(this);
  82865. };
  82866. /**
  82867. * Serialize the skeleton in a JSON object
  82868. * @returns a JSON object
  82869. */
  82870. Skeleton.prototype.serialize = function () {
  82871. var serializationObject = {};
  82872. serializationObject.name = this.name;
  82873. serializationObject.id = this.id;
  82874. if (this.dimensionsAtRest) {
  82875. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  82876. }
  82877. serializationObject.bones = [];
  82878. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82879. for (var index = 0; index < this.bones.length; index++) {
  82880. var bone = this.bones[index];
  82881. var parent_2 = bone.getParent();
  82882. var serializedBone = {
  82883. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  82884. name: bone.name,
  82885. matrix: bone.getBaseMatrix().toArray(),
  82886. rest: bone.getRestPose().toArray()
  82887. };
  82888. serializationObject.bones.push(serializedBone);
  82889. if (bone.length) {
  82890. serializedBone.length = bone.length;
  82891. }
  82892. if (bone.metadata) {
  82893. serializedBone.metadata = bone.metadata;
  82894. }
  82895. if (bone.animations && bone.animations.length > 0) {
  82896. serializedBone.animation = bone.animations[0].serialize();
  82897. }
  82898. serializationObject.ranges = [];
  82899. for (var name in this._ranges) {
  82900. var source = this._ranges[name];
  82901. if (!source) {
  82902. continue;
  82903. }
  82904. var range = {};
  82905. range.name = name;
  82906. range.from = source.from;
  82907. range.to = source.to;
  82908. serializationObject.ranges.push(range);
  82909. }
  82910. }
  82911. return serializationObject;
  82912. };
  82913. /**
  82914. * Creates a new skeleton from serialized data
  82915. * @param parsedSkeleton defines the serialized data
  82916. * @param scene defines the hosting scene
  82917. * @returns a new skeleton
  82918. */
  82919. Skeleton.Parse = function (parsedSkeleton, scene) {
  82920. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  82921. if (parsedSkeleton.dimensionsAtRest) {
  82922. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  82923. }
  82924. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  82925. var index;
  82926. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  82927. var parsedBone = parsedSkeleton.bones[index];
  82928. var parentBone = null;
  82929. if (parsedBone.parentBoneIndex > -1) {
  82930. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  82931. }
  82932. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  82933. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  82934. if (parsedBone.length) {
  82935. bone.length = parsedBone.length;
  82936. }
  82937. if (parsedBone.metadata) {
  82938. bone.metadata = parsedBone.metadata;
  82939. }
  82940. if (parsedBone.animation) {
  82941. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  82942. }
  82943. }
  82944. // placed after bones, so createAnimationRange can cascade down
  82945. if (parsedSkeleton.ranges) {
  82946. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  82947. var data = parsedSkeleton.ranges[index];
  82948. skeleton.createAnimationRange(data.name, data.from, data.to);
  82949. }
  82950. }
  82951. return skeleton;
  82952. };
  82953. /**
  82954. * Compute all node absolute transforms
  82955. * @param forceUpdate defines if computation must be done even if cache is up to date
  82956. */
  82957. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  82958. if (forceUpdate === void 0) { forceUpdate = false; }
  82959. var renderId = this._scene.getRenderId();
  82960. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  82961. this.bones[0].computeAbsoluteTransforms();
  82962. this._lastAbsoluteTransformsUpdateId = renderId;
  82963. }
  82964. };
  82965. /**
  82966. * Gets the root pose matrix
  82967. * @returns a matrix
  82968. */
  82969. Skeleton.prototype.getPoseMatrix = function () {
  82970. var poseMatrix = null;
  82971. if (this._meshesWithPoseMatrix.length > 0) {
  82972. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  82973. }
  82974. return poseMatrix;
  82975. };
  82976. /**
  82977. * Sorts bones per internal index
  82978. */
  82979. Skeleton.prototype.sortBones = function () {
  82980. var bones = new Array();
  82981. var visited = new Array(this.bones.length);
  82982. for (var index = 0; index < this.bones.length; index++) {
  82983. this._sortBones(index, bones, visited);
  82984. }
  82985. this.bones = bones;
  82986. };
  82987. Skeleton.prototype._sortBones = function (index, bones, visited) {
  82988. if (visited[index]) {
  82989. return;
  82990. }
  82991. visited[index] = true;
  82992. var bone = this.bones[index];
  82993. if (bone._index === undefined) {
  82994. bone._index = index;
  82995. }
  82996. var parentBone = bone.getParent();
  82997. if (parentBone) {
  82998. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  82999. }
  83000. bones.push(bone);
  83001. };
  83002. return Skeleton;
  83003. }());
  83004. BABYLON.Skeleton = Skeleton;
  83005. })(BABYLON || (BABYLON = {}));
  83006. //# sourceMappingURL=babylon.skeleton.js.map
  83007. var BABYLON;
  83008. (function (BABYLON) {
  83009. ;
  83010. /**
  83011. * This groups tools to convert HDR texture to native colors array.
  83012. */
  83013. var HDRTools = /** @class */ (function () {
  83014. function HDRTools() {
  83015. }
  83016. HDRTools.Ldexp = function (mantissa, exponent) {
  83017. if (exponent > 1023) {
  83018. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  83019. }
  83020. if (exponent < -1074) {
  83021. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  83022. }
  83023. return mantissa * Math.pow(2, exponent);
  83024. };
  83025. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  83026. if (exponent > 0) { /*nonzero pixel*/
  83027. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  83028. float32array[index + 0] = red * exponent;
  83029. float32array[index + 1] = green * exponent;
  83030. float32array[index + 2] = blue * exponent;
  83031. }
  83032. else {
  83033. float32array[index + 0] = 0;
  83034. float32array[index + 1] = 0;
  83035. float32array[index + 2] = 0;
  83036. }
  83037. };
  83038. HDRTools.readStringLine = function (uint8array, startIndex) {
  83039. var line = "";
  83040. var character = "";
  83041. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83042. character = String.fromCharCode(uint8array[i]);
  83043. if (character == "\n") {
  83044. break;
  83045. }
  83046. line += character;
  83047. }
  83048. return line;
  83049. };
  83050. /**
  83051. * Reads header information from an RGBE texture stored in a native array.
  83052. * More information on this format are available here:
  83053. * https://en.wikipedia.org/wiki/RGBE_image_format
  83054. *
  83055. * @param uint8array The binary file stored in native array.
  83056. * @return The header information.
  83057. */
  83058. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83059. var height = 0;
  83060. var width = 0;
  83061. var line = this.readStringLine(uint8array, 0);
  83062. if (line[0] != '#' || line[1] != '?') {
  83063. throw "Bad HDR Format.";
  83064. }
  83065. var endOfHeader = false;
  83066. var findFormat = false;
  83067. var lineIndex = 0;
  83068. do {
  83069. lineIndex += (line.length + 1);
  83070. line = this.readStringLine(uint8array, lineIndex);
  83071. if (line == "FORMAT=32-bit_rle_rgbe") {
  83072. findFormat = true;
  83073. }
  83074. else if (line.length == 0) {
  83075. endOfHeader = true;
  83076. }
  83077. } while (!endOfHeader);
  83078. if (!findFormat) {
  83079. throw "HDR Bad header format, unsupported FORMAT";
  83080. }
  83081. lineIndex += (line.length + 1);
  83082. line = this.readStringLine(uint8array, lineIndex);
  83083. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83084. var match = sizeRegexp.exec(line);
  83085. // TODO. Support +Y and -X if needed.
  83086. if (!match || match.length < 3) {
  83087. throw "HDR Bad header format, no size";
  83088. }
  83089. width = parseInt(match[2]);
  83090. height = parseInt(match[1]);
  83091. if (width < 8 || width > 0x7fff) {
  83092. throw "HDR Bad header format, unsupported size";
  83093. }
  83094. lineIndex += (line.length + 1);
  83095. return {
  83096. height: height,
  83097. width: width,
  83098. dataPosition: lineIndex
  83099. };
  83100. };
  83101. /**
  83102. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83103. * This RGBE texture needs to store the information as a panorama.
  83104. *
  83105. * More information on this format are available here:
  83106. * https://en.wikipedia.org/wiki/RGBE_image_format
  83107. *
  83108. * @param buffer The binary file stored in an array buffer.
  83109. * @param size The expected size of the extracted cubemap.
  83110. * @return The Cube Map information.
  83111. */
  83112. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83113. var uint8array = new Uint8Array(buffer);
  83114. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83115. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83116. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83117. return cubeMapData;
  83118. };
  83119. /**
  83120. * Returns the pixels data extracted from an RGBE texture.
  83121. * This pixels will be stored left to right up to down in the R G B order in one array.
  83122. *
  83123. * More information on this format are available here:
  83124. * https://en.wikipedia.org/wiki/RGBE_image_format
  83125. *
  83126. * @param uint8array The binary file stored in an array buffer.
  83127. * @param hdrInfo The header information of the file.
  83128. * @return The pixels data in RGB right to left up to down order.
  83129. */
  83130. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83131. // Keep for multi format supports.
  83132. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83133. };
  83134. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83135. var num_scanlines = hdrInfo.height;
  83136. var scanline_width = hdrInfo.width;
  83137. var a, b, c, d, count;
  83138. var dataIndex = hdrInfo.dataPosition;
  83139. var index = 0, endIndex = 0, i = 0;
  83140. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83141. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83142. // 3 channels of 4 bytes per pixel in float.
  83143. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83144. var resultArray = new Float32Array(resultBuffer);
  83145. // read in each successive scanline
  83146. while (num_scanlines > 0) {
  83147. a = uint8array[dataIndex++];
  83148. b = uint8array[dataIndex++];
  83149. c = uint8array[dataIndex++];
  83150. d = uint8array[dataIndex++];
  83151. if (a != 2 || b != 2 || (c & 0x80)) {
  83152. // this file is not run length encoded
  83153. throw "HDR Bad header format, not RLE";
  83154. }
  83155. if (((c << 8) | d) != scanline_width) {
  83156. throw "HDR Bad header format, wrong scan line width";
  83157. }
  83158. index = 0;
  83159. // read each of the four channels for the scanline into the buffer
  83160. for (i = 0; i < 4; i++) {
  83161. endIndex = (i + 1) * scanline_width;
  83162. while (index < endIndex) {
  83163. a = uint8array[dataIndex++];
  83164. b = uint8array[dataIndex++];
  83165. if (a > 128) {
  83166. // a run of the same value
  83167. count = a - 128;
  83168. if ((count == 0) || (count > endIndex - index)) {
  83169. throw "HDR Bad Format, bad scanline data (run)";
  83170. }
  83171. while (count-- > 0) {
  83172. scanLineArray[index++] = b;
  83173. }
  83174. }
  83175. else {
  83176. // a non-run
  83177. count = a;
  83178. if ((count == 0) || (count > endIndex - index)) {
  83179. throw "HDR Bad Format, bad scanline data (non-run)";
  83180. }
  83181. scanLineArray[index++] = b;
  83182. if (--count > 0) {
  83183. for (var j = 0; j < count; j++) {
  83184. scanLineArray[index++] = uint8array[dataIndex++];
  83185. }
  83186. }
  83187. }
  83188. }
  83189. }
  83190. // now convert data from buffer into floats
  83191. for (i = 0; i < scanline_width; i++) {
  83192. a = scanLineArray[i];
  83193. b = scanLineArray[i + scanline_width];
  83194. c = scanLineArray[i + 2 * scanline_width];
  83195. d = scanLineArray[i + 3 * scanline_width];
  83196. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83197. }
  83198. num_scanlines--;
  83199. }
  83200. return resultArray;
  83201. };
  83202. return HDRTools;
  83203. }());
  83204. BABYLON.HDRTools = HDRTools;
  83205. })(BABYLON || (BABYLON = {}));
  83206. //# sourceMappingURL=babylon.hdr.js.map
  83207. var BABYLON;
  83208. (function (BABYLON) {
  83209. /**
  83210. * This represents a texture coming from an HDR input.
  83211. *
  83212. * The only supported format is currently panorama picture stored in RGBE format.
  83213. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83214. */
  83215. var HDRCubeTexture = /** @class */ (function (_super) {
  83216. __extends(HDRCubeTexture, _super);
  83217. /**
  83218. * Instantiates an HDRTexture from the following parameters.
  83219. *
  83220. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83221. * @param scene The scene the texture will be used in
  83222. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83223. * @param noMipmap Forces to not generate the mipmap if true
  83224. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83225. * @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)
  83226. * @param reserved Reserved flag for internal use.
  83227. */
  83228. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83229. if (noMipmap === void 0) { noMipmap = false; }
  83230. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83231. if (gammaSpace === void 0) { gammaSpace = false; }
  83232. if (reserved === void 0) { reserved = false; }
  83233. if (onLoad === void 0) { onLoad = null; }
  83234. if (onError === void 0) { onError = null; }
  83235. var _this = _super.call(this, scene) || this;
  83236. _this._generateHarmonics = true;
  83237. _this._onLoad = null;
  83238. _this._onError = null;
  83239. /**
  83240. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83241. */
  83242. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83243. _this._isBlocking = true;
  83244. _this._rotationY = 0;
  83245. /**
  83246. * Gets or sets the center of the bounding box associated with the cube texture
  83247. * It must define where the camera used to render the texture was set
  83248. */
  83249. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83250. if (!url) {
  83251. return _this;
  83252. }
  83253. _this.name = url;
  83254. _this.url = url;
  83255. _this.hasAlpha = false;
  83256. _this.isCube = true;
  83257. _this._textureMatrix = BABYLON.Matrix.Identity();
  83258. _this._onLoad = onLoad;
  83259. _this._onError = onError;
  83260. _this.gammaSpace = gammaSpace;
  83261. _this._noMipmap = noMipmap;
  83262. _this._size = size;
  83263. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83264. if (!_this._texture) {
  83265. if (!scene.useDelayedTextureLoading) {
  83266. _this.loadTexture();
  83267. }
  83268. else {
  83269. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83270. }
  83271. }
  83272. return _this;
  83273. }
  83274. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83275. /**
  83276. * Gets wether or not the texture is blocking during loading.
  83277. */
  83278. get: function () {
  83279. return this._isBlocking;
  83280. },
  83281. /**
  83282. * Sets wether or not the texture is blocking during loading.
  83283. */
  83284. set: function (value) {
  83285. this._isBlocking = value;
  83286. },
  83287. enumerable: true,
  83288. configurable: true
  83289. });
  83290. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83291. /**
  83292. * Gets texture matrix rotation angle around Y axis radians.
  83293. */
  83294. get: function () {
  83295. return this._rotationY;
  83296. },
  83297. /**
  83298. * Sets texture matrix rotation angle around Y axis in radians.
  83299. */
  83300. set: function (value) {
  83301. this._rotationY = value;
  83302. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83303. },
  83304. enumerable: true,
  83305. configurable: true
  83306. });
  83307. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83308. get: function () {
  83309. return this._boundingBoxSize;
  83310. },
  83311. /**
  83312. * Gets or sets the size of the bounding box associated with the cube texture
  83313. * When defined, the cubemap will switch to local mode
  83314. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83315. * @example https://www.babylonjs-playground.com/#RNASML
  83316. */
  83317. set: function (value) {
  83318. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83319. return;
  83320. }
  83321. this._boundingBoxSize = value;
  83322. var scene = this.getScene();
  83323. if (scene) {
  83324. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83325. }
  83326. },
  83327. enumerable: true,
  83328. configurable: true
  83329. });
  83330. /**
  83331. * Occurs when the file is raw .hdr file.
  83332. */
  83333. HDRCubeTexture.prototype.loadTexture = function () {
  83334. var _this = this;
  83335. var callback = function (buffer) {
  83336. _this.lodGenerationOffset = 0.0;
  83337. _this.lodGenerationScale = 0.8;
  83338. var scene = _this.getScene();
  83339. if (!scene) {
  83340. return null;
  83341. }
  83342. // Extract the raw linear data.
  83343. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83344. // Generate harmonics if needed.
  83345. if (_this._generateHarmonics) {
  83346. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83347. _this.sphericalPolynomial = sphericalPolynomial;
  83348. }
  83349. var results = [];
  83350. var byteArray = null;
  83351. // Push each faces.
  83352. for (var j = 0; j < 6; j++) {
  83353. // Create uintarray fallback.
  83354. if (!scene.getEngine().getCaps().textureFloat) {
  83355. // 3 channels of 1 bytes per pixel in bytes.
  83356. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83357. byteArray = new Uint8Array(byteBuffer);
  83358. }
  83359. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83360. // If special cases.
  83361. if (_this.gammaSpace || byteArray) {
  83362. for (var i = 0; i < _this._size * _this._size; i++) {
  83363. // Put in gamma space if requested.
  83364. if (_this.gammaSpace) {
  83365. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83366. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83367. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83368. }
  83369. // Convert to int texture for fallback.
  83370. if (byteArray) {
  83371. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83372. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83373. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83374. // May use luminance instead if the result is not accurate.
  83375. var max = Math.max(Math.max(r, g), b);
  83376. if (max > 255) {
  83377. var scale = 255 / max;
  83378. r *= scale;
  83379. g *= scale;
  83380. b *= scale;
  83381. }
  83382. byteArray[(i * 3) + 0] = r;
  83383. byteArray[(i * 3) + 1] = g;
  83384. byteArray[(i * 3) + 2] = b;
  83385. }
  83386. }
  83387. }
  83388. if (byteArray) {
  83389. results.push(byteArray);
  83390. }
  83391. else {
  83392. results.push(dataFace);
  83393. }
  83394. }
  83395. return results;
  83396. };
  83397. var scene = this.getScene();
  83398. if (scene) {
  83399. 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);
  83400. }
  83401. };
  83402. HDRCubeTexture.prototype.clone = function () {
  83403. var scene = this.getScene();
  83404. if (!scene) {
  83405. return this;
  83406. }
  83407. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83408. // Base texture
  83409. newTexture.level = this.level;
  83410. newTexture.wrapU = this.wrapU;
  83411. newTexture.wrapV = this.wrapV;
  83412. newTexture.coordinatesIndex = this.coordinatesIndex;
  83413. newTexture.coordinatesMode = this.coordinatesMode;
  83414. return newTexture;
  83415. };
  83416. // Methods
  83417. HDRCubeTexture.prototype.delayLoad = function () {
  83418. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83419. return;
  83420. }
  83421. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83422. this._texture = this._getFromCache(this.url, this._noMipmap);
  83423. if (!this._texture) {
  83424. this.loadTexture();
  83425. }
  83426. };
  83427. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83428. return this._textureMatrix;
  83429. };
  83430. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83431. this._textureMatrix = value;
  83432. };
  83433. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83434. var texture = null;
  83435. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83436. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83437. texture.name = parsedTexture.name;
  83438. texture.hasAlpha = parsedTexture.hasAlpha;
  83439. texture.level = parsedTexture.level;
  83440. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83441. texture.isBlocking = parsedTexture.isBlocking;
  83442. }
  83443. if (texture) {
  83444. if (parsedTexture.boundingBoxPosition) {
  83445. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83446. }
  83447. if (parsedTexture.boundingBoxSize) {
  83448. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83449. }
  83450. if (parsedTexture.rotationY) {
  83451. texture.rotationY = parsedTexture.rotationY;
  83452. }
  83453. }
  83454. return texture;
  83455. };
  83456. HDRCubeTexture.prototype.serialize = function () {
  83457. if (!this.name) {
  83458. return null;
  83459. }
  83460. var serializationObject = {};
  83461. serializationObject.name = this.name;
  83462. serializationObject.hasAlpha = this.hasAlpha;
  83463. serializationObject.isCube = true;
  83464. serializationObject.level = this.level;
  83465. serializationObject.size = this._size;
  83466. serializationObject.coordinatesMode = this.coordinatesMode;
  83467. serializationObject.useInGammaSpace = this.gammaSpace;
  83468. serializationObject.generateHarmonics = this._generateHarmonics;
  83469. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83470. serializationObject.noMipmap = this._noMipmap;
  83471. serializationObject.isBlocking = this._isBlocking;
  83472. serializationObject.rotationY = this._rotationY;
  83473. return serializationObject;
  83474. };
  83475. HDRCubeTexture._facesMapping = [
  83476. "right",
  83477. "left",
  83478. "up",
  83479. "down",
  83480. "front",
  83481. "back"
  83482. ];
  83483. return HDRCubeTexture;
  83484. }(BABYLON.BaseTexture));
  83485. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83486. })(BABYLON || (BABYLON = {}));
  83487. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83488. var BABYLON;
  83489. (function (BABYLON) {
  83490. /**
  83491. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  83492. */
  83493. var PanoramaToCubeMapTools = /** @class */ (function () {
  83494. function PanoramaToCubeMapTools() {
  83495. }
  83496. /**
  83497. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  83498. *
  83499. * @param float32Array The source data.
  83500. * @param inputWidth The width of the input panorama.
  83501. * @param inputhHeight The height of the input panorama.
  83502. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  83503. * @return The cubemap data
  83504. */
  83505. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  83506. if (!float32Array) {
  83507. throw "ConvertPanoramaToCubemap: input cannot be null";
  83508. }
  83509. if (float32Array.length != inputWidth * inputHeight * 3) {
  83510. throw "ConvertPanoramaToCubemap: input size is wrong";
  83511. }
  83512. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  83513. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  83514. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  83515. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  83516. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  83517. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  83518. return {
  83519. front: textureFront,
  83520. back: textureBack,
  83521. left: textureLeft,
  83522. right: textureRight,
  83523. up: textureUp,
  83524. down: textureDown,
  83525. size: size,
  83526. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  83527. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  83528. gammaSpace: false,
  83529. };
  83530. };
  83531. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  83532. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  83533. var textureArray = new Float32Array(buffer);
  83534. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  83535. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  83536. var dy = 1 / texSize;
  83537. var fy = 0;
  83538. for (var y = 0; y < texSize; y++) {
  83539. var xv1 = faceData[0];
  83540. var xv2 = faceData[2];
  83541. for (var x = 0; x < texSize; x++) {
  83542. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  83543. v.normalize();
  83544. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  83545. // 3 channels per pixels
  83546. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  83547. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  83548. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  83549. xv1 = xv1.add(rotDX1);
  83550. xv2 = xv2.add(rotDX2);
  83551. }
  83552. fy += dy;
  83553. }
  83554. return textureArray;
  83555. };
  83556. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  83557. var theta = Math.atan2(vDir.z, vDir.x);
  83558. var phi = Math.acos(vDir.y);
  83559. while (theta < -Math.PI)
  83560. theta += 2 * Math.PI;
  83561. while (theta > Math.PI)
  83562. theta -= 2 * Math.PI;
  83563. var dx = theta / Math.PI;
  83564. var dy = phi / Math.PI;
  83565. // recenter.
  83566. dx = dx * 0.5 + 0.5;
  83567. var px = Math.round(dx * inputWidth);
  83568. if (px < 0)
  83569. px = 0;
  83570. else if (px >= inputWidth)
  83571. px = inputWidth - 1;
  83572. var py = Math.round(dy * inputHeight);
  83573. if (py < 0)
  83574. py = 0;
  83575. else if (py >= inputHeight)
  83576. py = inputHeight - 1;
  83577. var inputY = (inputHeight - py - 1);
  83578. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  83579. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  83580. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  83581. return {
  83582. r: r,
  83583. g: g,
  83584. b: b
  83585. };
  83586. };
  83587. PanoramaToCubeMapTools.FACE_FRONT = [
  83588. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83589. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83590. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83591. new BABYLON.Vector3(1.0, 1.0, -1.0)
  83592. ];
  83593. PanoramaToCubeMapTools.FACE_BACK = [
  83594. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83595. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83596. new BABYLON.Vector3(1.0, 1.0, 1.0),
  83597. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  83598. ];
  83599. PanoramaToCubeMapTools.FACE_RIGHT = [
  83600. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83601. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83602. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83603. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83604. ];
  83605. PanoramaToCubeMapTools.FACE_LEFT = [
  83606. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83607. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83608. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83609. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  83610. ];
  83611. PanoramaToCubeMapTools.FACE_DOWN = [
  83612. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83613. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83614. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83615. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83616. ];
  83617. PanoramaToCubeMapTools.FACE_UP = [
  83618. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83619. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83620. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83621. new BABYLON.Vector3(1.0, -1.0, -1.0)
  83622. ];
  83623. return PanoramaToCubeMapTools;
  83624. }());
  83625. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  83626. })(BABYLON || (BABYLON = {}));
  83627. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  83628. var BABYLON;
  83629. (function (BABYLON) {
  83630. var IndexedVector2 = /** @class */ (function (_super) {
  83631. __extends(IndexedVector2, _super);
  83632. function IndexedVector2(original, index) {
  83633. var _this = _super.call(this, original.x, original.y) || this;
  83634. _this.index = index;
  83635. return _this;
  83636. }
  83637. return IndexedVector2;
  83638. }(BABYLON.Vector2));
  83639. var PolygonPoints = /** @class */ (function () {
  83640. function PolygonPoints() {
  83641. this.elements = new Array();
  83642. }
  83643. PolygonPoints.prototype.add = function (originalPoints) {
  83644. var _this = this;
  83645. var result = new Array();
  83646. originalPoints.forEach(function (point) {
  83647. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83648. var newPoint = new IndexedVector2(point, _this.elements.length);
  83649. result.push(newPoint);
  83650. _this.elements.push(newPoint);
  83651. }
  83652. });
  83653. return result;
  83654. };
  83655. PolygonPoints.prototype.computeBounds = function () {
  83656. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83657. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83658. this.elements.forEach(function (point) {
  83659. // x
  83660. if (point.x < lmin.x) {
  83661. lmin.x = point.x;
  83662. }
  83663. else if (point.x > lmax.x) {
  83664. lmax.x = point.x;
  83665. }
  83666. // y
  83667. if (point.y < lmin.y) {
  83668. lmin.y = point.y;
  83669. }
  83670. else if (point.y > lmax.y) {
  83671. lmax.y = point.y;
  83672. }
  83673. });
  83674. return {
  83675. min: lmin,
  83676. max: lmax,
  83677. width: lmax.x - lmin.x,
  83678. height: lmax.y - lmin.y
  83679. };
  83680. };
  83681. return PolygonPoints;
  83682. }());
  83683. var Polygon = /** @class */ (function () {
  83684. function Polygon() {
  83685. }
  83686. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83687. return [
  83688. new BABYLON.Vector2(xmin, ymin),
  83689. new BABYLON.Vector2(xmax, ymin),
  83690. new BABYLON.Vector2(xmax, ymax),
  83691. new BABYLON.Vector2(xmin, ymax)
  83692. ];
  83693. };
  83694. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83695. if (cx === void 0) { cx = 0; }
  83696. if (cy === void 0) { cy = 0; }
  83697. if (numberOfSides === void 0) { numberOfSides = 32; }
  83698. var result = new Array();
  83699. var angle = 0;
  83700. var increment = (Math.PI * 2) / numberOfSides;
  83701. for (var i = 0; i < numberOfSides; i++) {
  83702. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83703. angle -= increment;
  83704. }
  83705. return result;
  83706. };
  83707. Polygon.Parse = function (input) {
  83708. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83709. var i, result = [];
  83710. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83711. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83712. }
  83713. return result;
  83714. };
  83715. Polygon.StartingAt = function (x, y) {
  83716. return BABYLON.Path2.StartingAt(x, y);
  83717. };
  83718. return Polygon;
  83719. }());
  83720. BABYLON.Polygon = Polygon;
  83721. var PolygonMeshBuilder = /** @class */ (function () {
  83722. function PolygonMeshBuilder(name, contours, scene) {
  83723. this._points = new PolygonPoints();
  83724. this._outlinepoints = new PolygonPoints();
  83725. this._holes = new Array();
  83726. this._epoints = new Array();
  83727. this._eholes = new Array();
  83728. this._name = name;
  83729. this._scene = scene;
  83730. var points;
  83731. if (contours instanceof BABYLON.Path2) {
  83732. points = contours.getPoints();
  83733. }
  83734. else {
  83735. points = contours;
  83736. }
  83737. this._addToepoint(points);
  83738. this._points.add(points);
  83739. this._outlinepoints.add(points);
  83740. if (typeof earcut === 'undefined') {
  83741. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83742. }
  83743. }
  83744. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83745. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83746. var p = points_1[_i];
  83747. this._epoints.push(p.x, p.y);
  83748. }
  83749. };
  83750. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83751. this._points.add(hole);
  83752. var holepoints = new PolygonPoints();
  83753. holepoints.add(hole);
  83754. this._holes.push(holepoints);
  83755. this._eholes.push(this._epoints.length / 2);
  83756. this._addToepoint(hole);
  83757. return this;
  83758. };
  83759. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83760. var _this = this;
  83761. if (updatable === void 0) { updatable = false; }
  83762. if (depth === void 0) { depth = 0; }
  83763. var result = new BABYLON.Mesh(this._name, this._scene);
  83764. var normals = new Array();
  83765. var positions = new Array();
  83766. var uvs = new Array();
  83767. var bounds = this._points.computeBounds();
  83768. this._points.elements.forEach(function (p) {
  83769. normals.push(0, 1.0, 0);
  83770. positions.push(p.x, 0, p.y);
  83771. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83772. });
  83773. var indices = new Array();
  83774. var res = earcut(this._epoints, this._eholes, 2);
  83775. for (var i = 0; i < res.length; i++) {
  83776. indices.push(res[i]);
  83777. }
  83778. if (depth > 0) {
  83779. var positionscount = (positions.length / 3); //get the current pointcount
  83780. this._points.elements.forEach(function (p) {
  83781. normals.push(0, -1.0, 0);
  83782. positions.push(p.x, -depth, p.y);
  83783. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83784. });
  83785. var totalCount = indices.length;
  83786. for (var i = 0; i < totalCount; i += 3) {
  83787. var i0 = indices[i + 0];
  83788. var i1 = indices[i + 1];
  83789. var i2 = indices[i + 2];
  83790. indices.push(i2 + positionscount);
  83791. indices.push(i1 + positionscount);
  83792. indices.push(i0 + positionscount);
  83793. }
  83794. //Add the sides
  83795. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83796. this._holes.forEach(function (hole) {
  83797. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83798. });
  83799. }
  83800. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83801. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83802. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83803. result.setIndices(indices);
  83804. return result;
  83805. };
  83806. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83807. var StartIndex = positions.length / 3;
  83808. var ulength = 0;
  83809. for (var i = 0; i < points.elements.length; i++) {
  83810. var p = points.elements[i];
  83811. var p1;
  83812. if ((i + 1) > points.elements.length - 1) {
  83813. p1 = points.elements[0];
  83814. }
  83815. else {
  83816. p1 = points.elements[i + 1];
  83817. }
  83818. positions.push(p.x, 0, p.y);
  83819. positions.push(p.x, -depth, p.y);
  83820. positions.push(p1.x, 0, p1.y);
  83821. positions.push(p1.x, -depth, p1.y);
  83822. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83823. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83824. var v3 = v2.subtract(v1);
  83825. var v4 = new BABYLON.Vector3(0, 1, 0);
  83826. var vn = BABYLON.Vector3.Cross(v3, v4);
  83827. vn = vn.normalize();
  83828. uvs.push(ulength / bounds.width, 0);
  83829. uvs.push(ulength / bounds.width, 1);
  83830. ulength += v3.length();
  83831. uvs.push((ulength / bounds.width), 0);
  83832. uvs.push((ulength / bounds.width), 1);
  83833. if (!flip) {
  83834. normals.push(-vn.x, -vn.y, -vn.z);
  83835. normals.push(-vn.x, -vn.y, -vn.z);
  83836. normals.push(-vn.x, -vn.y, -vn.z);
  83837. normals.push(-vn.x, -vn.y, -vn.z);
  83838. indices.push(StartIndex);
  83839. indices.push(StartIndex + 1);
  83840. indices.push(StartIndex + 2);
  83841. indices.push(StartIndex + 1);
  83842. indices.push(StartIndex + 3);
  83843. indices.push(StartIndex + 2);
  83844. }
  83845. else {
  83846. normals.push(vn.x, vn.y, vn.z);
  83847. normals.push(vn.x, vn.y, vn.z);
  83848. normals.push(vn.x, vn.y, vn.z);
  83849. normals.push(vn.x, vn.y, vn.z);
  83850. indices.push(StartIndex);
  83851. indices.push(StartIndex + 2);
  83852. indices.push(StartIndex + 1);
  83853. indices.push(StartIndex + 1);
  83854. indices.push(StartIndex + 2);
  83855. indices.push(StartIndex + 3);
  83856. }
  83857. StartIndex += 4;
  83858. }
  83859. ;
  83860. };
  83861. return PolygonMeshBuilder;
  83862. }());
  83863. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83864. })(BABYLON || (BABYLON = {}));
  83865. //# sourceMappingURL=babylon.polygonMesh.js.map
  83866. var BABYLON;
  83867. (function (BABYLON) {
  83868. // Unique ID when we import meshes from Babylon to CSG
  83869. var currentCSGMeshId = 0;
  83870. // # class Vertex
  83871. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83872. // one to provide additional features like texture coordinates and vertex
  83873. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83874. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83875. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83876. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83877. // is not used anywhere else.
  83878. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83879. var Vertex = /** @class */ (function () {
  83880. function Vertex(pos, normal, uv) {
  83881. this.pos = pos;
  83882. this.normal = normal;
  83883. this.uv = uv;
  83884. }
  83885. Vertex.prototype.clone = function () {
  83886. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83887. };
  83888. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83889. // orientation of a polygon is flipped.
  83890. Vertex.prototype.flip = function () {
  83891. this.normal = this.normal.scale(-1);
  83892. };
  83893. // Create a new vertex between this vertex and `other` by linearly
  83894. // interpolating all properties using a parameter of `t`. Subclasses should
  83895. // override this to interpolate additional properties.
  83896. Vertex.prototype.interpolate = function (other, t) {
  83897. 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));
  83898. };
  83899. return Vertex;
  83900. }());
  83901. // # class Plane
  83902. // Represents a plane in 3D space.
  83903. var Plane = /** @class */ (function () {
  83904. function Plane(normal, w) {
  83905. this.normal = normal;
  83906. this.w = w;
  83907. }
  83908. Plane.FromPoints = function (a, b, c) {
  83909. var v0 = c.subtract(a);
  83910. var v1 = b.subtract(a);
  83911. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83912. return null;
  83913. }
  83914. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83915. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83916. };
  83917. Plane.prototype.clone = function () {
  83918. return new Plane(this.normal.clone(), this.w);
  83919. };
  83920. Plane.prototype.flip = function () {
  83921. this.normal.scaleInPlace(-1);
  83922. this.w = -this.w;
  83923. };
  83924. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83925. // fragments in the appropriate lists. Coplanar polygons go into either
  83926. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83927. // respect to this plane. Polygons in front or in back of this plane go into
  83928. // either `front` or `back`.
  83929. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83930. var COPLANAR = 0;
  83931. var FRONT = 1;
  83932. var BACK = 2;
  83933. var SPANNING = 3;
  83934. // Classify each point as well as the entire polygon into one of the above
  83935. // four classes.
  83936. var polygonType = 0;
  83937. var types = [];
  83938. var i;
  83939. var t;
  83940. for (i = 0; i < polygon.vertices.length; i++) {
  83941. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83942. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83943. polygonType |= type;
  83944. types.push(type);
  83945. }
  83946. // Put the polygon in the correct list, splitting it when necessary.
  83947. switch (polygonType) {
  83948. case COPLANAR:
  83949. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83950. break;
  83951. case FRONT:
  83952. front.push(polygon);
  83953. break;
  83954. case BACK:
  83955. back.push(polygon);
  83956. break;
  83957. case SPANNING:
  83958. var f = [], b = [];
  83959. for (i = 0; i < polygon.vertices.length; i++) {
  83960. var j = (i + 1) % polygon.vertices.length;
  83961. var ti = types[i], tj = types[j];
  83962. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83963. if (ti !== BACK)
  83964. f.push(vi);
  83965. if (ti !== FRONT)
  83966. b.push(ti !== BACK ? vi.clone() : vi);
  83967. if ((ti | tj) === SPANNING) {
  83968. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83969. var v = vi.interpolate(vj, t);
  83970. f.push(v);
  83971. b.push(v.clone());
  83972. }
  83973. }
  83974. var poly;
  83975. if (f.length >= 3) {
  83976. poly = new Polygon(f, polygon.shared);
  83977. if (poly.plane)
  83978. front.push(poly);
  83979. }
  83980. if (b.length >= 3) {
  83981. poly = new Polygon(b, polygon.shared);
  83982. if (poly.plane)
  83983. back.push(poly);
  83984. }
  83985. break;
  83986. }
  83987. };
  83988. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83989. // point is on the plane.
  83990. Plane.EPSILON = 1e-5;
  83991. return Plane;
  83992. }());
  83993. // # class Polygon
  83994. // Represents a convex polygon. The vertices used to initialize a polygon must
  83995. // be coplanar and form a convex loop.
  83996. //
  83997. // Each convex polygon has a `shared` property, which is shared between all
  83998. // polygons that are clones of each other or were split from the same polygon.
  83999. // This can be used to define per-polygon properties (such as surface color).
  84000. var Polygon = /** @class */ (function () {
  84001. function Polygon(vertices, shared) {
  84002. this.vertices = vertices;
  84003. this.shared = shared;
  84004. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  84005. }
  84006. Polygon.prototype.clone = function () {
  84007. var vertices = this.vertices.map(function (v) { return v.clone(); });
  84008. return new Polygon(vertices, this.shared);
  84009. };
  84010. Polygon.prototype.flip = function () {
  84011. this.vertices.reverse().map(function (v) { v.flip(); });
  84012. this.plane.flip();
  84013. };
  84014. return Polygon;
  84015. }());
  84016. // # class Node
  84017. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  84018. // by picking a polygon to split along. That polygon (and all other coplanar
  84019. // polygons) are added directly to that node and the other polygons are added to
  84020. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  84021. // no distinction between internal and leaf nodes.
  84022. var Node = /** @class */ (function () {
  84023. function Node(polygons) {
  84024. this.plane = null;
  84025. this.front = null;
  84026. this.back = null;
  84027. this.polygons = new Array();
  84028. if (polygons) {
  84029. this.build(polygons);
  84030. }
  84031. }
  84032. Node.prototype.clone = function () {
  84033. var node = new Node();
  84034. node.plane = this.plane && this.plane.clone();
  84035. node.front = this.front && this.front.clone();
  84036. node.back = this.back && this.back.clone();
  84037. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84038. return node;
  84039. };
  84040. // Convert solid space to empty space and empty space to solid space.
  84041. Node.prototype.invert = function () {
  84042. for (var i = 0; i < this.polygons.length; i++) {
  84043. this.polygons[i].flip();
  84044. }
  84045. if (this.plane) {
  84046. this.plane.flip();
  84047. }
  84048. if (this.front) {
  84049. this.front.invert();
  84050. }
  84051. if (this.back) {
  84052. this.back.invert();
  84053. }
  84054. var temp = this.front;
  84055. this.front = this.back;
  84056. this.back = temp;
  84057. };
  84058. // Recursively remove all polygons in `polygons` that are inside this BSP
  84059. // tree.
  84060. Node.prototype.clipPolygons = function (polygons) {
  84061. if (!this.plane)
  84062. return polygons.slice();
  84063. var front = new Array(), back = new Array();
  84064. for (var i = 0; i < polygons.length; i++) {
  84065. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84066. }
  84067. if (this.front) {
  84068. front = this.front.clipPolygons(front);
  84069. }
  84070. if (this.back) {
  84071. back = this.back.clipPolygons(back);
  84072. }
  84073. else {
  84074. back = [];
  84075. }
  84076. return front.concat(back);
  84077. };
  84078. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84079. // `bsp`.
  84080. Node.prototype.clipTo = function (bsp) {
  84081. this.polygons = bsp.clipPolygons(this.polygons);
  84082. if (this.front)
  84083. this.front.clipTo(bsp);
  84084. if (this.back)
  84085. this.back.clipTo(bsp);
  84086. };
  84087. // Return a list of all polygons in this BSP tree.
  84088. Node.prototype.allPolygons = function () {
  84089. var polygons = this.polygons.slice();
  84090. if (this.front)
  84091. polygons = polygons.concat(this.front.allPolygons());
  84092. if (this.back)
  84093. polygons = polygons.concat(this.back.allPolygons());
  84094. return polygons;
  84095. };
  84096. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84097. // new polygons are filtered down to the bottom of the tree and become new
  84098. // nodes there. Each set of polygons is partitioned using the first polygon
  84099. // (no heuristic is used to pick a good split).
  84100. Node.prototype.build = function (polygons) {
  84101. if (!polygons.length)
  84102. return;
  84103. if (!this.plane)
  84104. this.plane = polygons[0].plane.clone();
  84105. var front = new Array(), back = new Array();
  84106. for (var i = 0; i < polygons.length; i++) {
  84107. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84108. }
  84109. if (front.length) {
  84110. if (!this.front)
  84111. this.front = new Node();
  84112. this.front.build(front);
  84113. }
  84114. if (back.length) {
  84115. if (!this.back)
  84116. this.back = new Node();
  84117. this.back.build(back);
  84118. }
  84119. };
  84120. return Node;
  84121. }());
  84122. var CSG = /** @class */ (function () {
  84123. function CSG() {
  84124. this.polygons = new Array();
  84125. }
  84126. // Convert BABYLON.Mesh to BABYLON.CSG
  84127. CSG.FromMesh = function (mesh) {
  84128. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84129. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84130. if (mesh instanceof BABYLON.Mesh) {
  84131. mesh.computeWorldMatrix(true);
  84132. matrix = mesh.getWorldMatrix();
  84133. meshPosition = mesh.position.clone();
  84134. meshRotation = mesh.rotation.clone();
  84135. if (mesh.rotationQuaternion) {
  84136. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84137. }
  84138. meshScaling = mesh.scaling.clone();
  84139. }
  84140. else {
  84141. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84142. }
  84143. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84144. var subMeshes = mesh.subMeshes;
  84145. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84146. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84147. vertices = [];
  84148. for (var j = 0; j < 3; j++) {
  84149. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84150. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84151. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84152. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84153. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84154. vertex = new Vertex(position, normal, uv);
  84155. vertices.push(vertex);
  84156. }
  84157. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84158. // To handle the case of degenerated triangle
  84159. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84160. if (polygon.plane)
  84161. polygons.push(polygon);
  84162. }
  84163. }
  84164. var csg = CSG.FromPolygons(polygons);
  84165. csg.matrix = matrix;
  84166. csg.position = meshPosition;
  84167. csg.rotation = meshRotation;
  84168. csg.scaling = meshScaling;
  84169. csg.rotationQuaternion = meshRotationQuaternion;
  84170. currentCSGMeshId++;
  84171. return csg;
  84172. };
  84173. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84174. CSG.FromPolygons = function (polygons) {
  84175. var csg = new CSG();
  84176. csg.polygons = polygons;
  84177. return csg;
  84178. };
  84179. CSG.prototype.clone = function () {
  84180. var csg = new CSG();
  84181. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84182. csg.copyTransformAttributes(this);
  84183. return csg;
  84184. };
  84185. CSG.prototype.union = function (csg) {
  84186. var a = new Node(this.clone().polygons);
  84187. var b = new Node(csg.clone().polygons);
  84188. a.clipTo(b);
  84189. b.clipTo(a);
  84190. b.invert();
  84191. b.clipTo(a);
  84192. b.invert();
  84193. a.build(b.allPolygons());
  84194. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84195. };
  84196. CSG.prototype.unionInPlace = function (csg) {
  84197. var a = new Node(this.polygons);
  84198. var b = new Node(csg.polygons);
  84199. a.clipTo(b);
  84200. b.clipTo(a);
  84201. b.invert();
  84202. b.clipTo(a);
  84203. b.invert();
  84204. a.build(b.allPolygons());
  84205. this.polygons = a.allPolygons();
  84206. };
  84207. CSG.prototype.subtract = function (csg) {
  84208. var a = new Node(this.clone().polygons);
  84209. var b = new Node(csg.clone().polygons);
  84210. a.invert();
  84211. a.clipTo(b);
  84212. b.clipTo(a);
  84213. b.invert();
  84214. b.clipTo(a);
  84215. b.invert();
  84216. a.build(b.allPolygons());
  84217. a.invert();
  84218. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84219. };
  84220. CSG.prototype.subtractInPlace = function (csg) {
  84221. var a = new Node(this.polygons);
  84222. var b = new Node(csg.polygons);
  84223. a.invert();
  84224. a.clipTo(b);
  84225. b.clipTo(a);
  84226. b.invert();
  84227. b.clipTo(a);
  84228. b.invert();
  84229. a.build(b.allPolygons());
  84230. a.invert();
  84231. this.polygons = a.allPolygons();
  84232. };
  84233. CSG.prototype.intersect = function (csg) {
  84234. var a = new Node(this.clone().polygons);
  84235. var b = new Node(csg.clone().polygons);
  84236. a.invert();
  84237. b.clipTo(a);
  84238. b.invert();
  84239. a.clipTo(b);
  84240. b.clipTo(a);
  84241. a.build(b.allPolygons());
  84242. a.invert();
  84243. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84244. };
  84245. CSG.prototype.intersectInPlace = function (csg) {
  84246. var a = new Node(this.polygons);
  84247. var b = new Node(csg.polygons);
  84248. a.invert();
  84249. b.clipTo(a);
  84250. b.invert();
  84251. a.clipTo(b);
  84252. b.clipTo(a);
  84253. a.build(b.allPolygons());
  84254. a.invert();
  84255. this.polygons = a.allPolygons();
  84256. };
  84257. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84258. // not modified.
  84259. CSG.prototype.inverse = function () {
  84260. var csg = this.clone();
  84261. csg.inverseInPlace();
  84262. return csg;
  84263. };
  84264. CSG.prototype.inverseInPlace = function () {
  84265. this.polygons.map(function (p) { p.flip(); });
  84266. };
  84267. // This is used to keep meshes transformations so they can be restored
  84268. // when we build back a Babylon Mesh
  84269. // NB : All CSG operations are performed in world coordinates
  84270. CSG.prototype.copyTransformAttributes = function (csg) {
  84271. this.matrix = csg.matrix;
  84272. this.position = csg.position;
  84273. this.rotation = csg.rotation;
  84274. this.scaling = csg.scaling;
  84275. this.rotationQuaternion = csg.rotationQuaternion;
  84276. return this;
  84277. };
  84278. // Build Raw mesh from CSG
  84279. // Coordinates here are in world space
  84280. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84281. var matrix = this.matrix.clone();
  84282. matrix.invert();
  84283. 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;
  84284. if (keepSubMeshes) {
  84285. // Sort Polygons, since subMeshes are indices range
  84286. polygons.sort(function (a, b) {
  84287. if (a.shared.meshId === b.shared.meshId) {
  84288. return a.shared.subMeshId - b.shared.subMeshId;
  84289. }
  84290. else {
  84291. return a.shared.meshId - b.shared.meshId;
  84292. }
  84293. });
  84294. }
  84295. for (var i = 0, il = polygons.length; i < il; i++) {
  84296. polygon = polygons[i];
  84297. // Building SubMeshes
  84298. if (!subMesh_dict[polygon.shared.meshId]) {
  84299. subMesh_dict[polygon.shared.meshId] = {};
  84300. }
  84301. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84302. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84303. indexStart: +Infinity,
  84304. indexEnd: -Infinity,
  84305. materialIndex: polygon.shared.materialIndex
  84306. };
  84307. }
  84308. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84309. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84310. polygonIndices[0] = 0;
  84311. polygonIndices[1] = j - 1;
  84312. polygonIndices[2] = j;
  84313. for (var k = 0; k < 3; k++) {
  84314. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84315. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84316. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84317. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84318. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84319. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84320. // Check if 2 points can be merged
  84321. if (!(typeof vertex_idx !== 'undefined' &&
  84322. normals[vertex_idx * 3] === localNormal.x &&
  84323. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84324. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84325. uvs[vertex_idx * 2] === uv.x &&
  84326. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84327. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84328. uvs.push(uv.x, uv.y);
  84329. normals.push(normal.x, normal.y, normal.z);
  84330. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84331. }
  84332. indices.push(vertex_idx);
  84333. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84334. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84335. currentIndex++;
  84336. }
  84337. }
  84338. }
  84339. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84340. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84341. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84342. mesh.setIndices(indices, null);
  84343. if (keepSubMeshes) {
  84344. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84345. var materialIndexOffset = 0, materialMaxIndex;
  84346. mesh.subMeshes = new Array();
  84347. for (var m in subMesh_dict) {
  84348. materialMaxIndex = -1;
  84349. for (var sm in subMesh_dict[m]) {
  84350. subMesh_obj = subMesh_dict[m][sm];
  84351. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84352. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84353. }
  84354. materialIndexOffset += ++materialMaxIndex;
  84355. }
  84356. }
  84357. return mesh;
  84358. };
  84359. // Build Mesh from CSG taking material and transforms into account
  84360. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84361. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84362. mesh.material = material;
  84363. mesh.position.copyFrom(this.position);
  84364. mesh.rotation.copyFrom(this.rotation);
  84365. if (this.rotationQuaternion) {
  84366. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84367. }
  84368. mesh.scaling.copyFrom(this.scaling);
  84369. mesh.computeWorldMatrix(true);
  84370. return mesh;
  84371. };
  84372. return CSG;
  84373. }());
  84374. BABYLON.CSG = CSG;
  84375. })(BABYLON || (BABYLON = {}));
  84376. //# sourceMappingURL=babylon.csg.js.map
  84377. var BABYLON;
  84378. (function (BABYLON) {
  84379. var LensFlare = /** @class */ (function () {
  84380. function LensFlare(size, position, color, imgUrl, system) {
  84381. this.size = size;
  84382. this.position = position;
  84383. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84384. this.color = color || new BABYLON.Color3(1, 1, 1);
  84385. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84386. this._system = system;
  84387. system.lensFlares.push(this);
  84388. }
  84389. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84390. return new LensFlare(size, position, color, imgUrl, system);
  84391. };
  84392. LensFlare.prototype.dispose = function () {
  84393. if (this.texture) {
  84394. this.texture.dispose();
  84395. }
  84396. // Remove from scene
  84397. var index = this._system.lensFlares.indexOf(this);
  84398. this._system.lensFlares.splice(index, 1);
  84399. };
  84400. ;
  84401. return LensFlare;
  84402. }());
  84403. BABYLON.LensFlare = LensFlare;
  84404. })(BABYLON || (BABYLON = {}));
  84405. //# sourceMappingURL=babylon.lensFlare.js.map
  84406. var BABYLON;
  84407. (function (BABYLON) {
  84408. // Adds the parser to the scene parsers.
  84409. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84410. // Lens flares
  84411. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84412. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84413. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84414. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84415. container.lensFlareSystems.push(lf);
  84416. }
  84417. }
  84418. });
  84419. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84420. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84421. if (this.lensFlareSystems[index].name === name) {
  84422. return this.lensFlareSystems[index];
  84423. }
  84424. }
  84425. return null;
  84426. };
  84427. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84428. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84429. if (this.lensFlareSystems[index].id === id) {
  84430. return this.lensFlareSystems[index];
  84431. }
  84432. }
  84433. return null;
  84434. };
  84435. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84436. var index = this.lensFlareSystems.indexOf(toRemove);
  84437. if (index !== -1) {
  84438. this.lensFlareSystems.splice(index, 1);
  84439. }
  84440. return index;
  84441. };
  84442. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84443. this.lensFlareSystems.push(newLensFlareSystem);
  84444. };
  84445. /**
  84446. * Defines the lens flare scene component responsible to manage any lens flares
  84447. * in a given scene.
  84448. */
  84449. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84450. /**
  84451. * Creates a new instance of the component for the given scene
  84452. * @param scene Defines the scene to register the component in
  84453. */
  84454. function LensFlareSystemSceneComponent(scene) {
  84455. /**
  84456. * The component name helpfull to identify the component in the list of scene components.
  84457. */
  84458. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84459. this.scene = scene;
  84460. scene.lensFlareSystems = new Array();
  84461. }
  84462. /**
  84463. * Registers the component in a given scene
  84464. */
  84465. LensFlareSystemSceneComponent.prototype.register = function () {
  84466. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84467. };
  84468. /**
  84469. * Rebuilds the elements related to this component in case of
  84470. * context lost for instance.
  84471. */
  84472. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84473. // Nothing to do for lens flare
  84474. };
  84475. /**
  84476. * Adds all the element from the container to the scene
  84477. * @param container the container holding the elements
  84478. */
  84479. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84480. var _this = this;
  84481. if (!container.lensFlareSystems) {
  84482. return;
  84483. }
  84484. container.lensFlareSystems.forEach(function (o) {
  84485. _this.scene.addLensFlareSystem(o);
  84486. });
  84487. };
  84488. /**
  84489. * Removes all the elements in the container from the scene
  84490. * @param container contains the elements to remove
  84491. */
  84492. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84493. var _this = this;
  84494. if (!container.lensFlareSystems) {
  84495. return;
  84496. }
  84497. container.lensFlareSystems.forEach(function (o) {
  84498. _this.scene.removeLensFlareSystem(o);
  84499. });
  84500. };
  84501. /**
  84502. * Serializes the component data to the specified json object
  84503. * @param serializationObject The object to serialize to
  84504. */
  84505. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84506. // Lens flares
  84507. serializationObject.lensFlareSystems = [];
  84508. var lensFlareSystems = this.scene.lensFlareSystems;
  84509. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84510. var lensFlareSystem = lensFlareSystems_1[_i];
  84511. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84512. }
  84513. };
  84514. /**
  84515. * Disposes the component and the associated ressources.
  84516. */
  84517. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84518. var lensFlareSystems = this.scene.lensFlareSystems;
  84519. while (lensFlareSystems.length) {
  84520. lensFlareSystems[0].dispose();
  84521. }
  84522. };
  84523. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84524. // Lens flares
  84525. if (this.scene.lensFlaresEnabled) {
  84526. var lensFlareSystems = this.scene.lensFlareSystems;
  84527. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84528. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84529. var lensFlareSystem = lensFlareSystems_2[_i];
  84530. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84531. lensFlareSystem.render();
  84532. }
  84533. }
  84534. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84535. }
  84536. };
  84537. return LensFlareSystemSceneComponent;
  84538. }());
  84539. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84540. })(BABYLON || (BABYLON = {}));
  84541. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84542. var BABYLON;
  84543. (function (BABYLON) {
  84544. var LensFlareSystem = /** @class */ (function () {
  84545. function LensFlareSystem(name, emitter, scene) {
  84546. this.name = name;
  84547. this.lensFlares = new Array();
  84548. this.borderLimit = 300;
  84549. this.viewportBorder = 0;
  84550. this.layerMask = 0x0FFFFFFF;
  84551. this._vertexBuffers = {};
  84552. this._isEnabled = true;
  84553. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84554. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84555. if (!component) {
  84556. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84557. scene._addComponent(component);
  84558. }
  84559. this._emitter = emitter;
  84560. this.id = name;
  84561. scene.lensFlareSystems.push(this);
  84562. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84563. var engine = scene.getEngine();
  84564. // VBO
  84565. var vertices = [];
  84566. vertices.push(1, 1);
  84567. vertices.push(-1, 1);
  84568. vertices.push(-1, -1);
  84569. vertices.push(1, -1);
  84570. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84571. // Indices
  84572. var indices = [];
  84573. indices.push(0);
  84574. indices.push(1);
  84575. indices.push(2);
  84576. indices.push(0);
  84577. indices.push(2);
  84578. indices.push(3);
  84579. this._indexBuffer = engine.createIndexBuffer(indices);
  84580. // Effects
  84581. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84582. }
  84583. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84584. get: function () {
  84585. return this._isEnabled;
  84586. },
  84587. set: function (value) {
  84588. this._isEnabled = value;
  84589. },
  84590. enumerable: true,
  84591. configurable: true
  84592. });
  84593. LensFlareSystem.prototype.getScene = function () {
  84594. return this._scene;
  84595. };
  84596. LensFlareSystem.prototype.getEmitter = function () {
  84597. return this._emitter;
  84598. };
  84599. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84600. this._emitter = newEmitter;
  84601. };
  84602. LensFlareSystem.prototype.getEmitterPosition = function () {
  84603. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84604. };
  84605. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84606. var position = this.getEmitterPosition();
  84607. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84608. this._positionX = position.x;
  84609. this._positionY = position.y;
  84610. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84611. if (this.viewportBorder > 0) {
  84612. globalViewport.x -= this.viewportBorder;
  84613. globalViewport.y -= this.viewportBorder;
  84614. globalViewport.width += this.viewportBorder * 2;
  84615. globalViewport.height += this.viewportBorder * 2;
  84616. position.x += this.viewportBorder;
  84617. position.y += this.viewportBorder;
  84618. this._positionX += this.viewportBorder;
  84619. this._positionY += this.viewportBorder;
  84620. }
  84621. if (position.z > 0) {
  84622. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84623. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84624. return true;
  84625. }
  84626. return true;
  84627. }
  84628. return false;
  84629. };
  84630. LensFlareSystem.prototype._isVisible = function () {
  84631. if (!this._isEnabled || !this._scene.activeCamera) {
  84632. return false;
  84633. }
  84634. var emitterPosition = this.getEmitterPosition();
  84635. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84636. var distance = direction.length();
  84637. direction.normalize();
  84638. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84639. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84640. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84641. };
  84642. LensFlareSystem.prototype.render = function () {
  84643. if (!this._effect.isReady() || !this._scene.activeCamera)
  84644. return false;
  84645. var engine = this._scene.getEngine();
  84646. var viewport = this._scene.activeCamera.viewport;
  84647. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84648. // Position
  84649. if (!this.computeEffectivePosition(globalViewport)) {
  84650. return false;
  84651. }
  84652. // Visibility
  84653. if (!this._isVisible()) {
  84654. return false;
  84655. }
  84656. // Intensity
  84657. var awayX;
  84658. var awayY;
  84659. if (this._positionX < this.borderLimit + globalViewport.x) {
  84660. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84661. }
  84662. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84663. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84664. }
  84665. else {
  84666. awayX = 0;
  84667. }
  84668. if (this._positionY < this.borderLimit + globalViewport.y) {
  84669. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84670. }
  84671. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84672. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84673. }
  84674. else {
  84675. awayY = 0;
  84676. }
  84677. var away = (awayX > awayY) ? awayX : awayY;
  84678. away -= this.viewportBorder;
  84679. if (away > this.borderLimit) {
  84680. away = this.borderLimit;
  84681. }
  84682. var intensity = 1.0 - (away / this.borderLimit);
  84683. if (intensity < 0) {
  84684. return false;
  84685. }
  84686. if (intensity > 1.0) {
  84687. intensity = 1.0;
  84688. }
  84689. if (this.viewportBorder > 0) {
  84690. globalViewport.x += this.viewportBorder;
  84691. globalViewport.y += this.viewportBorder;
  84692. globalViewport.width -= this.viewportBorder * 2;
  84693. globalViewport.height -= this.viewportBorder * 2;
  84694. this._positionX -= this.viewportBorder;
  84695. this._positionY -= this.viewportBorder;
  84696. }
  84697. // Position
  84698. var centerX = globalViewport.x + globalViewport.width / 2;
  84699. var centerY = globalViewport.y + globalViewport.height / 2;
  84700. var distX = centerX - this._positionX;
  84701. var distY = centerY - this._positionY;
  84702. // Effects
  84703. engine.enableEffect(this._effect);
  84704. engine.setState(false);
  84705. engine.setDepthBuffer(false);
  84706. // VBOs
  84707. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84708. // Flares
  84709. for (var index = 0; index < this.lensFlares.length; index++) {
  84710. var flare = this.lensFlares[index];
  84711. engine.setAlphaMode(flare.alphaMode);
  84712. var x = centerX - (distX * flare.position);
  84713. var y = centerY - (distY * flare.position);
  84714. var cw = flare.size;
  84715. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84716. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84717. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84718. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84719. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84720. // Texture
  84721. this._effect.setTexture("textureSampler", flare.texture);
  84722. // Color
  84723. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84724. // Draw order
  84725. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84726. }
  84727. engine.setDepthBuffer(true);
  84728. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84729. return true;
  84730. };
  84731. LensFlareSystem.prototype.dispose = function () {
  84732. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84733. if (vertexBuffer) {
  84734. vertexBuffer.dispose();
  84735. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84736. }
  84737. if (this._indexBuffer) {
  84738. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84739. this._indexBuffer = null;
  84740. }
  84741. while (this.lensFlares.length) {
  84742. this.lensFlares[0].dispose();
  84743. }
  84744. // Remove from scene
  84745. var index = this._scene.lensFlareSystems.indexOf(this);
  84746. this._scene.lensFlareSystems.splice(index, 1);
  84747. };
  84748. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84749. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84750. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84751. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84752. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84753. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84754. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84755. var parsedFlare = parsedLensFlareSystem.flares[index];
  84756. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84757. }
  84758. return lensFlareSystem;
  84759. };
  84760. LensFlareSystem.prototype.serialize = function () {
  84761. var serializationObject = {};
  84762. serializationObject.id = this.id;
  84763. serializationObject.name = this.name;
  84764. serializationObject.emitterId = this.getEmitter().id;
  84765. serializationObject.borderLimit = this.borderLimit;
  84766. serializationObject.flares = [];
  84767. for (var index = 0; index < this.lensFlares.length; index++) {
  84768. var flare = this.lensFlares[index];
  84769. serializationObject.flares.push({
  84770. size: flare.size,
  84771. position: flare.position,
  84772. color: flare.color.asArray(),
  84773. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84774. });
  84775. }
  84776. return serializationObject;
  84777. };
  84778. return LensFlareSystem;
  84779. }());
  84780. BABYLON.LensFlareSystem = LensFlareSystem;
  84781. })(BABYLON || (BABYLON = {}));
  84782. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84783. var BABYLON;
  84784. (function (BABYLON) {
  84785. /**
  84786. * This is a holder class for the physics joint created by the physics plugin.
  84787. * It holds a set of functions to control the underlying joint.
  84788. */
  84789. var PhysicsJoint = /** @class */ (function () {
  84790. function PhysicsJoint(type, jointData) {
  84791. this.type = type;
  84792. this.jointData = jointData;
  84793. jointData.nativeParams = jointData.nativeParams || {};
  84794. }
  84795. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84796. get: function () {
  84797. return this._physicsJoint;
  84798. },
  84799. set: function (newJoint) {
  84800. if (this._physicsJoint) {
  84801. //remove from the wolrd
  84802. }
  84803. this._physicsJoint = newJoint;
  84804. },
  84805. enumerable: true,
  84806. configurable: true
  84807. });
  84808. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84809. set: function (physicsPlugin) {
  84810. this._physicsPlugin = physicsPlugin;
  84811. },
  84812. enumerable: true,
  84813. configurable: true
  84814. });
  84815. /**
  84816. * Execute a function that is physics-plugin specific.
  84817. * @param {Function} func the function that will be executed.
  84818. * It accepts two parameters: the physics world and the physics joint.
  84819. */
  84820. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84821. func(this._physicsPlugin.world, this._physicsJoint);
  84822. };
  84823. //TODO check if the native joints are the same
  84824. //Joint Types
  84825. PhysicsJoint.DistanceJoint = 0;
  84826. PhysicsJoint.HingeJoint = 1;
  84827. PhysicsJoint.BallAndSocketJoint = 2;
  84828. PhysicsJoint.WheelJoint = 3;
  84829. PhysicsJoint.SliderJoint = 4;
  84830. //OIMO
  84831. PhysicsJoint.PrismaticJoint = 5;
  84832. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84833. PhysicsJoint.UniversalJoint = 6;
  84834. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84835. //Cannon
  84836. //Similar to a Ball-Joint. Different in params
  84837. PhysicsJoint.PointToPointJoint = 8;
  84838. //Cannon only at the moment
  84839. PhysicsJoint.SpringJoint = 9;
  84840. PhysicsJoint.LockJoint = 10;
  84841. return PhysicsJoint;
  84842. }());
  84843. BABYLON.PhysicsJoint = PhysicsJoint;
  84844. /**
  84845. * A class representing a physics distance joint.
  84846. */
  84847. var DistanceJoint = /** @class */ (function (_super) {
  84848. __extends(DistanceJoint, _super);
  84849. function DistanceJoint(jointData) {
  84850. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84851. }
  84852. /**
  84853. * Update the predefined distance.
  84854. */
  84855. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84856. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84857. };
  84858. return DistanceJoint;
  84859. }(PhysicsJoint));
  84860. BABYLON.DistanceJoint = DistanceJoint;
  84861. var MotorEnabledJoint = /** @class */ (function (_super) {
  84862. __extends(MotorEnabledJoint, _super);
  84863. function MotorEnabledJoint(type, jointData) {
  84864. return _super.call(this, type, jointData) || this;
  84865. }
  84866. /**
  84867. * Set the motor values.
  84868. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84869. * @param {number} force the force to apply
  84870. * @param {number} maxForce max force for this motor.
  84871. */
  84872. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84873. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84874. };
  84875. /**
  84876. * Set the motor's limits.
  84877. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84878. */
  84879. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84880. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84881. };
  84882. return MotorEnabledJoint;
  84883. }(PhysicsJoint));
  84884. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84885. /**
  84886. * This class represents a single hinge physics joint
  84887. */
  84888. var HingeJoint = /** @class */ (function (_super) {
  84889. __extends(HingeJoint, _super);
  84890. function HingeJoint(jointData) {
  84891. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84892. }
  84893. /**
  84894. * Set the motor values.
  84895. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84896. * @param {number} force the force to apply
  84897. * @param {number} maxForce max force for this motor.
  84898. */
  84899. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84900. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84901. };
  84902. /**
  84903. * Set the motor's limits.
  84904. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84905. */
  84906. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84907. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84908. };
  84909. return HingeJoint;
  84910. }(MotorEnabledJoint));
  84911. BABYLON.HingeJoint = HingeJoint;
  84912. /**
  84913. * This class represents a dual hinge physics joint (same as wheel joint)
  84914. */
  84915. var Hinge2Joint = /** @class */ (function (_super) {
  84916. __extends(Hinge2Joint, _super);
  84917. function Hinge2Joint(jointData) {
  84918. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84919. }
  84920. /**
  84921. * Set the motor values.
  84922. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84923. * @param {number} force the force to apply
  84924. * @param {number} maxForce max force for this motor.
  84925. * @param {motorIndex} the motor's index, 0 or 1.
  84926. */
  84927. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84928. if (motorIndex === void 0) { motorIndex = 0; }
  84929. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84930. };
  84931. /**
  84932. * Set the motor limits.
  84933. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84934. * @param {number} upperLimit the upper limit
  84935. * @param {number} lowerLimit lower limit
  84936. * @param {motorIndex} the motor's index, 0 or 1.
  84937. */
  84938. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84939. if (motorIndex === void 0) { motorIndex = 0; }
  84940. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84941. };
  84942. return Hinge2Joint;
  84943. }(MotorEnabledJoint));
  84944. BABYLON.Hinge2Joint = Hinge2Joint;
  84945. })(BABYLON || (BABYLON = {}));
  84946. //# sourceMappingURL=babylon.physicsJoint.js.map
  84947. var BABYLON;
  84948. (function (BABYLON) {
  84949. var PhysicsImpostor = /** @class */ (function () {
  84950. function PhysicsImpostor(object, type, _options, _scene) {
  84951. if (_options === void 0) { _options = { mass: 0 }; }
  84952. var _this = this;
  84953. this.object = object;
  84954. this.type = type;
  84955. this._options = _options;
  84956. this._scene = _scene;
  84957. this._bodyUpdateRequired = false;
  84958. this._onBeforePhysicsStepCallbacks = new Array();
  84959. this._onAfterPhysicsStepCallbacks = new Array();
  84960. this._onPhysicsCollideCallbacks = [];
  84961. this._deltaPosition = BABYLON.Vector3.Zero();
  84962. this._isDisposed = false;
  84963. //temp variables for parent rotation calculations
  84964. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84965. this._tmpQuat = new BABYLON.Quaternion();
  84966. this._tmpQuat2 = new BABYLON.Quaternion();
  84967. /**
  84968. * this function is executed by the physics engine.
  84969. */
  84970. this.beforeStep = function () {
  84971. if (!_this._physicsEngine) {
  84972. return;
  84973. }
  84974. _this.object.translate(_this._deltaPosition, -1);
  84975. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84976. _this.object.computeWorldMatrix(false);
  84977. if (_this.object.parent && _this.object.rotationQuaternion) {
  84978. _this.getParentsRotation();
  84979. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84980. }
  84981. else {
  84982. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84983. }
  84984. if (!_this._options.disableBidirectionalTransformation) {
  84985. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84986. }
  84987. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84988. func(_this);
  84989. });
  84990. };
  84991. /**
  84992. * this function is executed by the physics engine.
  84993. */
  84994. this.afterStep = function () {
  84995. if (!_this._physicsEngine) {
  84996. return;
  84997. }
  84998. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84999. func(_this);
  85000. });
  85001. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  85002. // object has now its world rotation. needs to be converted to local.
  85003. if (_this.object.parent && _this.object.rotationQuaternion) {
  85004. _this.getParentsRotation();
  85005. _this._tmpQuat.conjugateInPlace();
  85006. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  85007. }
  85008. // take the position set and make it the absolute position of this object.
  85009. _this.object.setAbsolutePosition(_this.object.position);
  85010. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  85011. _this.object.translate(_this._deltaPosition, 1);
  85012. };
  85013. /**
  85014. * Legacy collision detection event support
  85015. */
  85016. this.onCollideEvent = null;
  85017. //event and body object due to cannon's event-based architecture.
  85018. this.onCollide = function (e) {
  85019. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  85020. return;
  85021. }
  85022. if (!_this._physicsEngine) {
  85023. return;
  85024. }
  85025. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  85026. if (otherImpostor) {
  85027. // Legacy collision detection event support
  85028. if (_this.onCollideEvent) {
  85029. _this.onCollideEvent(_this, otherImpostor);
  85030. }
  85031. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85032. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85033. }).forEach(function (obj) {
  85034. obj.callback(_this, otherImpostor);
  85035. });
  85036. }
  85037. };
  85038. //sanity check!
  85039. if (!this.object) {
  85040. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85041. return;
  85042. }
  85043. //legacy support for old syntax.
  85044. if (!this._scene && object.getScene) {
  85045. this._scene = object.getScene();
  85046. }
  85047. if (!this._scene) {
  85048. return;
  85049. }
  85050. this._physicsEngine = this._scene.getPhysicsEngine();
  85051. if (!this._physicsEngine) {
  85052. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85053. }
  85054. else {
  85055. //set the object's quaternion, if not set
  85056. if (!this.object.rotationQuaternion) {
  85057. if (this.object.rotation) {
  85058. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85059. }
  85060. else {
  85061. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85062. }
  85063. }
  85064. //default options params
  85065. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85066. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85067. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85068. this._joints = [];
  85069. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85070. if (!this.object.parent || this._options.ignoreParent) {
  85071. this._init();
  85072. }
  85073. else if (this.object.parent.physicsImpostor) {
  85074. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85075. }
  85076. }
  85077. }
  85078. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85079. get: function () {
  85080. return this._isDisposed;
  85081. },
  85082. enumerable: true,
  85083. configurable: true
  85084. });
  85085. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85086. get: function () {
  85087. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85088. },
  85089. set: function (value) {
  85090. this.setMass(value);
  85091. },
  85092. enumerable: true,
  85093. configurable: true
  85094. });
  85095. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85096. get: function () {
  85097. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85098. },
  85099. set: function (value) {
  85100. if (!this._physicsEngine) {
  85101. return;
  85102. }
  85103. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85104. },
  85105. enumerable: true,
  85106. configurable: true
  85107. });
  85108. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85109. get: function () {
  85110. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85111. },
  85112. set: function (value) {
  85113. if (!this._physicsEngine) {
  85114. return;
  85115. }
  85116. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85117. },
  85118. enumerable: true,
  85119. configurable: true
  85120. });
  85121. /**
  85122. * This function will completly initialize this impostor.
  85123. * It will create a new body - but only if this mesh has no parent.
  85124. * If it has, this impostor will not be used other than to define the impostor
  85125. * of the child mesh.
  85126. */
  85127. PhysicsImpostor.prototype._init = function () {
  85128. if (!this._physicsEngine) {
  85129. return;
  85130. }
  85131. this._physicsEngine.removeImpostor(this);
  85132. this.physicsBody = null;
  85133. this._parent = this._parent || this._getPhysicsParent();
  85134. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85135. this._physicsEngine.addImpostor(this);
  85136. }
  85137. };
  85138. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85139. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85140. var parentMesh = this.object.parent;
  85141. return parentMesh.physicsImpostor;
  85142. }
  85143. return null;
  85144. };
  85145. /**
  85146. * Should a new body be generated.
  85147. */
  85148. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85149. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85150. };
  85151. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85152. this.forceUpdate();
  85153. };
  85154. /**
  85155. * Force a regeneration of this or the parent's impostor's body.
  85156. * Use under cautious - This will remove all joints already implemented.
  85157. */
  85158. PhysicsImpostor.prototype.forceUpdate = function () {
  85159. this._init();
  85160. if (this.parent && !this._options.ignoreParent) {
  85161. this.parent.forceUpdate();
  85162. }
  85163. };
  85164. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85165. /*public get mesh(): AbstractMesh {
  85166. return this._mesh;
  85167. }*/
  85168. /**
  85169. * Gets the body that holds this impostor. Either its own, or its parent.
  85170. */
  85171. get: function () {
  85172. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85173. },
  85174. /**
  85175. * Set the physics body. Used mainly by the physics engine/plugin
  85176. */
  85177. set: function (physicsBody) {
  85178. if (this._physicsBody && this._physicsEngine) {
  85179. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85180. }
  85181. this._physicsBody = physicsBody;
  85182. this.resetUpdateFlags();
  85183. },
  85184. enumerable: true,
  85185. configurable: true
  85186. });
  85187. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85188. get: function () {
  85189. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85190. },
  85191. set: function (value) {
  85192. this._parent = value;
  85193. },
  85194. enumerable: true,
  85195. configurable: true
  85196. });
  85197. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85198. this._bodyUpdateRequired = false;
  85199. };
  85200. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85201. if (this.object.getBoundingInfo) {
  85202. var q = this.object.rotationQuaternion;
  85203. //reset rotation
  85204. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85205. //calculate the world matrix with no rotation
  85206. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85207. var boundingInfo = this.object.getBoundingInfo();
  85208. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85209. //bring back the rotation
  85210. this.object.rotationQuaternion = q;
  85211. //calculate the world matrix with the new rotation
  85212. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85213. return size;
  85214. }
  85215. else {
  85216. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85217. }
  85218. };
  85219. PhysicsImpostor.prototype.getObjectCenter = function () {
  85220. if (this.object.getBoundingInfo) {
  85221. var boundingInfo = this.object.getBoundingInfo();
  85222. return boundingInfo.boundingBox.centerWorld;
  85223. }
  85224. else {
  85225. return this.object.position;
  85226. }
  85227. };
  85228. /**
  85229. * Get a specific parametes from the options parameter.
  85230. */
  85231. PhysicsImpostor.prototype.getParam = function (paramName) {
  85232. return this._options[paramName];
  85233. };
  85234. /**
  85235. * Sets a specific parameter in the options given to the physics plugin
  85236. */
  85237. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85238. this._options[paramName] = value;
  85239. this._bodyUpdateRequired = true;
  85240. };
  85241. /**
  85242. * Specifically change the body's mass option. Won't recreate the physics body object
  85243. */
  85244. PhysicsImpostor.prototype.setMass = function (mass) {
  85245. if (this.getParam("mass") !== mass) {
  85246. this.setParam("mass", mass);
  85247. }
  85248. if (this._physicsEngine) {
  85249. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85250. }
  85251. };
  85252. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85253. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85254. };
  85255. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85256. if (this._physicsEngine) {
  85257. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85258. }
  85259. };
  85260. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85261. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85262. };
  85263. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85264. if (this._physicsEngine) {
  85265. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85266. }
  85267. };
  85268. /**
  85269. * Execute a function with the physics plugin native code.
  85270. * Provide a function the will have two variables - the world object and the physics body object.
  85271. */
  85272. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85273. if (this._physicsEngine) {
  85274. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85275. }
  85276. };
  85277. /**
  85278. * Register a function that will be executed before the physics world is stepping forward.
  85279. */
  85280. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85281. this._onBeforePhysicsStepCallbacks.push(func);
  85282. };
  85283. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85284. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85285. if (index > -1) {
  85286. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85287. }
  85288. else {
  85289. BABYLON.Tools.Warn("Function to remove was not found");
  85290. }
  85291. };
  85292. /**
  85293. * Register a function that will be executed after the physics step
  85294. */
  85295. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85296. this._onAfterPhysicsStepCallbacks.push(func);
  85297. };
  85298. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85299. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85300. if (index > -1) {
  85301. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85302. }
  85303. else {
  85304. BABYLON.Tools.Warn("Function to remove was not found");
  85305. }
  85306. };
  85307. /**
  85308. * register a function that will be executed when this impostor collides against a different body.
  85309. */
  85310. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85311. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85312. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85313. };
  85314. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85315. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85316. var index = -1;
  85317. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85318. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85319. // chcek the arrays match
  85320. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85321. return collidedAgainstList.indexOf(impostor) > -1;
  85322. });
  85323. if (sameList) {
  85324. index = idx;
  85325. }
  85326. return sameList;
  85327. }
  85328. return false;
  85329. });
  85330. if (found) {
  85331. this._onPhysicsCollideCallbacks.splice(index, 1);
  85332. }
  85333. else {
  85334. BABYLON.Tools.Warn("Function to remove was not found");
  85335. }
  85336. };
  85337. PhysicsImpostor.prototype.getParentsRotation = function () {
  85338. var parent = this.object.parent;
  85339. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85340. while (parent) {
  85341. if (parent.rotationQuaternion) {
  85342. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85343. }
  85344. else {
  85345. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85346. }
  85347. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85348. parent = parent.parent;
  85349. }
  85350. return this._tmpQuat;
  85351. };
  85352. /**
  85353. * Apply a force
  85354. */
  85355. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85356. if (this._physicsEngine) {
  85357. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85358. }
  85359. return this;
  85360. };
  85361. /**
  85362. * Apply an impulse
  85363. */
  85364. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85365. if (this._physicsEngine) {
  85366. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85367. }
  85368. return this;
  85369. };
  85370. /**
  85371. * A help function to create a joint.
  85372. */
  85373. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85374. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85375. this.addJoint(otherImpostor, joint);
  85376. return this;
  85377. };
  85378. /**
  85379. * Add a joint to this impostor with a different impostor.
  85380. */
  85381. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85382. this._joints.push({
  85383. otherImpostor: otherImpostor,
  85384. joint: joint
  85385. });
  85386. if (this._physicsEngine) {
  85387. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85388. }
  85389. return this;
  85390. };
  85391. /**
  85392. * Will keep this body still, in a sleep mode.
  85393. */
  85394. PhysicsImpostor.prototype.sleep = function () {
  85395. if (this._physicsEngine) {
  85396. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85397. }
  85398. return this;
  85399. };
  85400. /**
  85401. * Wake the body up.
  85402. */
  85403. PhysicsImpostor.prototype.wakeUp = function () {
  85404. if (this._physicsEngine) {
  85405. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85406. }
  85407. return this;
  85408. };
  85409. PhysicsImpostor.prototype.clone = function (newObject) {
  85410. if (!newObject)
  85411. return null;
  85412. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85413. };
  85414. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85415. var _this = this;
  85416. //no dispose if no physics engine is available.
  85417. if (!this._physicsEngine) {
  85418. return;
  85419. }
  85420. this._joints.forEach(function (j) {
  85421. if (_this._physicsEngine) {
  85422. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85423. }
  85424. });
  85425. //dispose the physics body
  85426. this._physicsEngine.removeImpostor(this);
  85427. if (this.parent) {
  85428. this.parent.forceUpdate();
  85429. }
  85430. else {
  85431. /*this._object.getChildMeshes().forEach(function(mesh) {
  85432. if (mesh.physicsImpostor) {
  85433. if (disposeChildren) {
  85434. mesh.physicsImpostor.dispose();
  85435. mesh.physicsImpostor = null;
  85436. }
  85437. }
  85438. })*/
  85439. }
  85440. this._isDisposed = true;
  85441. };
  85442. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85443. this._deltaPosition.copyFrom(position);
  85444. };
  85445. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85446. if (!this._deltaRotation) {
  85447. this._deltaRotation = new BABYLON.Quaternion();
  85448. }
  85449. this._deltaRotation.copyFrom(rotation);
  85450. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85451. };
  85452. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85453. if (this._physicsEngine) {
  85454. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85455. }
  85456. return this;
  85457. };
  85458. PhysicsImpostor.prototype.getRadius = function () {
  85459. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85460. };
  85461. /**
  85462. * Sync a bone with this impostor
  85463. * @param bone The bone to sync to the impostor.
  85464. * @param boneMesh The mesh that the bone is influencing.
  85465. * @param jointPivot The pivot of the joint / bone in local space.
  85466. * @param distToJoint Optional distance from the impostor to the joint.
  85467. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85468. */
  85469. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85470. var tempVec = PhysicsImpostor._tmpVecs[0];
  85471. var mesh = this.object;
  85472. if (mesh.rotationQuaternion) {
  85473. if (adjustRotation) {
  85474. var tempQuat = PhysicsImpostor._tmpQuat;
  85475. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85476. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85477. }
  85478. else {
  85479. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85480. }
  85481. }
  85482. tempVec.x = 0;
  85483. tempVec.y = 0;
  85484. tempVec.z = 0;
  85485. if (jointPivot) {
  85486. tempVec.x = jointPivot.x;
  85487. tempVec.y = jointPivot.y;
  85488. tempVec.z = jointPivot.z;
  85489. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85490. if (distToJoint === undefined || distToJoint === null) {
  85491. distToJoint = jointPivot.length();
  85492. }
  85493. tempVec.x *= distToJoint;
  85494. tempVec.y *= distToJoint;
  85495. tempVec.z *= distToJoint;
  85496. }
  85497. if (bone.getParent()) {
  85498. tempVec.addInPlace(mesh.getAbsolutePosition());
  85499. bone.setAbsolutePosition(tempVec, boneMesh);
  85500. }
  85501. else {
  85502. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85503. boneMesh.position.x -= tempVec.x;
  85504. boneMesh.position.y -= tempVec.y;
  85505. boneMesh.position.z -= tempVec.z;
  85506. }
  85507. };
  85508. /**
  85509. * Sync impostor to a bone
  85510. * @param bone The bone that the impostor will be synced to.
  85511. * @param boneMesh The mesh that the bone is influencing.
  85512. * @param jointPivot The pivot of the joint / bone in local space.
  85513. * @param distToJoint Optional distance from the impostor to the joint.
  85514. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85515. * @param boneAxis Optional vector3 axis the bone is aligned with
  85516. */
  85517. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85518. var mesh = this.object;
  85519. if (mesh.rotationQuaternion) {
  85520. if (adjustRotation) {
  85521. var tempQuat = PhysicsImpostor._tmpQuat;
  85522. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85523. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85524. }
  85525. else {
  85526. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85527. }
  85528. }
  85529. var pos = PhysicsImpostor._tmpVecs[0];
  85530. var boneDir = PhysicsImpostor._tmpVecs[1];
  85531. if (!boneAxis) {
  85532. boneAxis = PhysicsImpostor._tmpVecs[2];
  85533. boneAxis.x = 0;
  85534. boneAxis.y = 1;
  85535. boneAxis.z = 0;
  85536. }
  85537. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85538. bone.getAbsolutePositionToRef(boneMesh, pos);
  85539. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85540. distToJoint = jointPivot.length();
  85541. }
  85542. if (distToJoint !== undefined && distToJoint !== null) {
  85543. pos.x += boneDir.x * distToJoint;
  85544. pos.y += boneDir.y * distToJoint;
  85545. pos.z += boneDir.z * distToJoint;
  85546. }
  85547. mesh.setAbsolutePosition(pos);
  85548. };
  85549. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85550. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85551. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85552. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85553. //Impostor types
  85554. PhysicsImpostor.NoImpostor = 0;
  85555. PhysicsImpostor.SphereImpostor = 1;
  85556. PhysicsImpostor.BoxImpostor = 2;
  85557. PhysicsImpostor.PlaneImpostor = 3;
  85558. PhysicsImpostor.MeshImpostor = 4;
  85559. PhysicsImpostor.CylinderImpostor = 7;
  85560. PhysicsImpostor.ParticleImpostor = 8;
  85561. PhysicsImpostor.HeightmapImpostor = 9;
  85562. return PhysicsImpostor;
  85563. }());
  85564. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85565. })(BABYLON || (BABYLON = {}));
  85566. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85567. var BABYLON;
  85568. (function (BABYLON) {
  85569. var PhysicsEngine = /** @class */ (function () {
  85570. function PhysicsEngine(gravity, _physicsPlugin) {
  85571. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85572. this._physicsPlugin = _physicsPlugin;
  85573. //new methods and parameters
  85574. this._impostors = [];
  85575. this._joints = [];
  85576. if (!this._physicsPlugin.isSupported()) {
  85577. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85578. + "Please make sure it is included.");
  85579. }
  85580. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85581. this.setGravity(gravity);
  85582. this.setTimeStep();
  85583. }
  85584. PhysicsEngine.prototype.setGravity = function (gravity) {
  85585. this.gravity = gravity;
  85586. this._physicsPlugin.setGravity(this.gravity);
  85587. };
  85588. /**
  85589. * Set the time step of the physics engine.
  85590. * default is 1/60.
  85591. * To slow it down, enter 1/600 for example.
  85592. * To speed it up, 1/30
  85593. * @param {number} newTimeStep the new timestep to apply to this world.
  85594. */
  85595. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85596. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85597. this._physicsPlugin.setTimeStep(newTimeStep);
  85598. };
  85599. /**
  85600. * Get the time step of the physics engine.
  85601. */
  85602. PhysicsEngine.prototype.getTimeStep = function () {
  85603. return this._physicsPlugin.getTimeStep();
  85604. };
  85605. PhysicsEngine.prototype.dispose = function () {
  85606. this._impostors.forEach(function (impostor) {
  85607. impostor.dispose();
  85608. });
  85609. this._physicsPlugin.dispose();
  85610. };
  85611. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85612. return this._physicsPlugin.name;
  85613. };
  85614. /**
  85615. * Adding a new impostor for the impostor tracking.
  85616. * This will be done by the impostor itself.
  85617. * @param {PhysicsImpostor} impostor the impostor to add
  85618. */
  85619. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85620. impostor.uniqueId = this._impostors.push(impostor);
  85621. //if no parent, generate the body
  85622. if (!impostor.parent) {
  85623. this._physicsPlugin.generatePhysicsBody(impostor);
  85624. }
  85625. };
  85626. /**
  85627. * Remove an impostor from the engine.
  85628. * This impostor and its mesh will not longer be updated by the physics engine.
  85629. * @param {PhysicsImpostor} impostor the impostor to remove
  85630. */
  85631. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85632. var index = this._impostors.indexOf(impostor);
  85633. if (index > -1) {
  85634. var removed = this._impostors.splice(index, 1);
  85635. //Is it needed?
  85636. if (removed.length) {
  85637. //this will also remove it from the world.
  85638. removed[0].physicsBody = null;
  85639. }
  85640. }
  85641. };
  85642. /**
  85643. * Add a joint to the physics engine
  85644. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85645. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85646. * @param {PhysicsJoint} the joint that will connect both impostors.
  85647. */
  85648. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85649. var impostorJoint = {
  85650. mainImpostor: mainImpostor,
  85651. connectedImpostor: connectedImpostor,
  85652. joint: joint
  85653. };
  85654. joint.physicsPlugin = this._physicsPlugin;
  85655. this._joints.push(impostorJoint);
  85656. this._physicsPlugin.generateJoint(impostorJoint);
  85657. };
  85658. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85659. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85660. return (impostorJoint.connectedImpostor === connectedImpostor
  85661. && impostorJoint.joint === joint
  85662. && impostorJoint.mainImpostor === mainImpostor);
  85663. });
  85664. if (matchingJoints.length) {
  85665. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85666. //TODO remove it from the list as well
  85667. }
  85668. };
  85669. /**
  85670. * Called by the scene. no need to call it.
  85671. */
  85672. PhysicsEngine.prototype._step = function (delta) {
  85673. var _this = this;
  85674. //check if any mesh has no body / requires an update
  85675. this._impostors.forEach(function (impostor) {
  85676. if (impostor.isBodyInitRequired()) {
  85677. _this._physicsPlugin.generatePhysicsBody(impostor);
  85678. }
  85679. });
  85680. if (delta > 0.1) {
  85681. delta = 0.1;
  85682. }
  85683. else if (delta <= 0) {
  85684. delta = 1.0 / 60.0;
  85685. }
  85686. this._physicsPlugin.executeStep(delta, this._impostors);
  85687. };
  85688. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85689. return this._physicsPlugin;
  85690. };
  85691. PhysicsEngine.prototype.getImpostors = function () {
  85692. return this._impostors;
  85693. };
  85694. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85695. for (var i = 0; i < this._impostors.length; ++i) {
  85696. if (this._impostors[i].object === object) {
  85697. return this._impostors[i];
  85698. }
  85699. }
  85700. return null;
  85701. };
  85702. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85703. for (var i = 0; i < this._impostors.length; ++i) {
  85704. if (this._impostors[i].physicsBody === body) {
  85705. return this._impostors[i];
  85706. }
  85707. }
  85708. return null;
  85709. };
  85710. // Statics
  85711. PhysicsEngine.Epsilon = 0.001;
  85712. return PhysicsEngine;
  85713. }());
  85714. BABYLON.PhysicsEngine = PhysicsEngine;
  85715. })(BABYLON || (BABYLON = {}));
  85716. //# sourceMappingURL=babylon.physicsEngine.js.map
  85717. var BABYLON;
  85718. (function (BABYLON) {
  85719. var PhysicsHelper = /** @class */ (function () {
  85720. function PhysicsHelper(scene) {
  85721. this._scene = scene;
  85722. this._physicsEngine = this._scene.getPhysicsEngine();
  85723. if (!this._physicsEngine) {
  85724. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85725. }
  85726. }
  85727. /**
  85728. * @param {Vector3} origin the origin of the explosion
  85729. * @param {number} radius the explosion radius
  85730. * @param {number} strength the explosion strength
  85731. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85732. */
  85733. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85734. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85735. if (!this._physicsEngine) {
  85736. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85737. return null;
  85738. }
  85739. var impostors = this._physicsEngine.getImpostors();
  85740. if (impostors.length === 0) {
  85741. return null;
  85742. }
  85743. var event = new PhysicsRadialExplosionEvent(this._scene);
  85744. impostors.forEach(function (impostor) {
  85745. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85746. if (!impostorForceAndContactPoint) {
  85747. return;
  85748. }
  85749. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85750. });
  85751. event.dispose(false);
  85752. return event;
  85753. };
  85754. /**
  85755. * @param {Vector3} origin the origin of the explosion
  85756. * @param {number} radius the explosion radius
  85757. * @param {number} strength the explosion strength
  85758. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85759. */
  85760. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85761. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85762. if (!this._physicsEngine) {
  85763. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85764. return null;
  85765. }
  85766. var impostors = this._physicsEngine.getImpostors();
  85767. if (impostors.length === 0) {
  85768. return null;
  85769. }
  85770. var event = new PhysicsRadialExplosionEvent(this._scene);
  85771. impostors.forEach(function (impostor) {
  85772. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85773. if (!impostorForceAndContactPoint) {
  85774. return;
  85775. }
  85776. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85777. });
  85778. event.dispose(false);
  85779. return event;
  85780. };
  85781. /**
  85782. * @param {Vector3} origin the origin of the explosion
  85783. * @param {number} radius the explosion radius
  85784. * @param {number} strength the explosion strength
  85785. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85786. */
  85787. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85788. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85789. if (!this._physicsEngine) {
  85790. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85791. return null;
  85792. }
  85793. var impostors = this._physicsEngine.getImpostors();
  85794. if (impostors.length === 0) {
  85795. return null;
  85796. }
  85797. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85798. event.dispose(false);
  85799. return event;
  85800. };
  85801. /**
  85802. * @param {Vector3} origin the origin of the updraft
  85803. * @param {number} radius the radius of the updraft
  85804. * @param {number} strength the strength of the updraft
  85805. * @param {number} height the height of the updraft
  85806. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85807. */
  85808. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85809. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85810. if (!this._physicsEngine) {
  85811. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85812. return null;
  85813. }
  85814. if (this._physicsEngine.getImpostors().length === 0) {
  85815. return null;
  85816. }
  85817. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85818. event.dispose(false);
  85819. return event;
  85820. };
  85821. /**
  85822. * @param {Vector3} origin the of the vortex
  85823. * @param {number} radius the radius of the vortex
  85824. * @param {number} strength the strength of the vortex
  85825. * @param {number} height the height of the vortex
  85826. */
  85827. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85828. if (!this._physicsEngine) {
  85829. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85830. return null;
  85831. }
  85832. if (this._physicsEngine.getImpostors().length === 0) {
  85833. return null;
  85834. }
  85835. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85836. event.dispose(false);
  85837. return event;
  85838. };
  85839. return PhysicsHelper;
  85840. }());
  85841. BABYLON.PhysicsHelper = PhysicsHelper;
  85842. /***** Radial explosion *****/
  85843. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85844. function PhysicsRadialExplosionEvent(scene) {
  85845. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85846. this._rays = [];
  85847. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85848. this._scene = scene;
  85849. }
  85850. /**
  85851. * Returns the data related to the radial explosion event (sphere & rays).
  85852. * @returns {PhysicsRadialExplosionEventData}
  85853. */
  85854. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85855. this._dataFetched = true;
  85856. return {
  85857. sphere: this._sphere,
  85858. rays: this._rays,
  85859. };
  85860. };
  85861. /**
  85862. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85863. * @param impostor
  85864. * @param {Vector3} origin the origin of the explosion
  85865. * @param {number} radius the explosion radius
  85866. * @param {number} strength the explosion strength
  85867. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85868. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85869. */
  85870. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85871. if (impostor.mass === 0) {
  85872. return null;
  85873. }
  85874. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85875. return null;
  85876. }
  85877. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85878. return null;
  85879. }
  85880. var impostorObjectCenter = impostor.getObjectCenter();
  85881. var direction = impostorObjectCenter.subtract(origin);
  85882. var ray = new BABYLON.Ray(origin, direction, radius);
  85883. this._rays.push(ray);
  85884. var hit = ray.intersectsMesh(impostor.object);
  85885. var contactPoint = hit.pickedPoint;
  85886. if (!contactPoint) {
  85887. return null;
  85888. }
  85889. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85890. if (distanceFromOrigin > radius) {
  85891. return null;
  85892. }
  85893. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85894. ? strength
  85895. : strength * (1 - (distanceFromOrigin / radius));
  85896. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85897. return { force: force, contactPoint: contactPoint };
  85898. };
  85899. /**
  85900. * Disposes the sphere.
  85901. * @param {bolean} force
  85902. */
  85903. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85904. var _this = this;
  85905. if (force === void 0) { force = true; }
  85906. if (force) {
  85907. this._sphere.dispose();
  85908. }
  85909. else {
  85910. setTimeout(function () {
  85911. if (!_this._dataFetched) {
  85912. _this._sphere.dispose();
  85913. }
  85914. }, 0);
  85915. }
  85916. };
  85917. /*** Helpers ***/
  85918. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85919. if (!this._sphere) {
  85920. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85921. this._sphere.isVisible = false;
  85922. }
  85923. };
  85924. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85925. var impostorObject = impostor.object;
  85926. this._prepareSphere();
  85927. this._sphere.position = origin;
  85928. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85929. this._sphere._updateBoundingInfo();
  85930. this._sphere.computeWorldMatrix(true);
  85931. return this._sphere.intersectsMesh(impostorObject, true);
  85932. };
  85933. return PhysicsRadialExplosionEvent;
  85934. }());
  85935. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85936. /***** Gravitational Field *****/
  85937. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85938. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85939. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85940. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85941. this._physicsHelper = physicsHelper;
  85942. this._scene = scene;
  85943. this._origin = origin;
  85944. this._radius = radius;
  85945. this._strength = strength;
  85946. this._falloff = falloff;
  85947. this._tickCallback = this._tick.bind(this);
  85948. }
  85949. /**
  85950. * Returns the data related to the gravitational field event (sphere).
  85951. * @returns {PhysicsGravitationalFieldEventData}
  85952. */
  85953. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85954. this._dataFetched = true;
  85955. return {
  85956. sphere: this._sphere,
  85957. };
  85958. };
  85959. /**
  85960. * Enables the gravitational field.
  85961. */
  85962. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85963. this._tickCallback.call(this);
  85964. this._scene.registerBeforeRender(this._tickCallback);
  85965. };
  85966. /**
  85967. * Disables the gravitational field.
  85968. */
  85969. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85970. this._scene.unregisterBeforeRender(this._tickCallback);
  85971. };
  85972. /**
  85973. * Disposes the sphere.
  85974. * @param {bolean} force
  85975. */
  85976. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85977. var _this = this;
  85978. if (force === void 0) { force = true; }
  85979. if (force) {
  85980. this._sphere.dispose();
  85981. }
  85982. else {
  85983. setTimeout(function () {
  85984. if (!_this._dataFetched) {
  85985. _this._sphere.dispose();
  85986. }
  85987. }, 0);
  85988. }
  85989. };
  85990. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85991. // Since the params won't change, we fetch the event only once
  85992. if (this._sphere) {
  85993. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85994. }
  85995. else {
  85996. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85997. if (radialExplosionEvent) {
  85998. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85999. }
  86000. }
  86001. };
  86002. return PhysicsGravitationalFieldEvent;
  86003. }());
  86004. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  86005. /***** Updraft *****/
  86006. var PhysicsUpdraftEvent = /** @class */ (function () {
  86007. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  86008. this._scene = _scene;
  86009. this._origin = _origin;
  86010. this._radius = _radius;
  86011. this._strength = _strength;
  86012. this._height = _height;
  86013. this._updraftMode = _updraftMode;
  86014. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86015. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  86016. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86017. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86018. this._physicsEngine = this._scene.getPhysicsEngine();
  86019. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86020. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86021. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86022. this._originDirection = this._origin.subtract(this._originTop).normalize();
  86023. }
  86024. this._tickCallback = this._tick.bind(this);
  86025. }
  86026. /**
  86027. * Returns the data related to the updraft event (cylinder).
  86028. * @returns {PhysicsUpdraftEventData}
  86029. */
  86030. PhysicsUpdraftEvent.prototype.getData = function () {
  86031. this._dataFetched = true;
  86032. return {
  86033. cylinder: this._cylinder,
  86034. };
  86035. };
  86036. /**
  86037. * Enables the updraft.
  86038. */
  86039. PhysicsUpdraftEvent.prototype.enable = function () {
  86040. this._tickCallback.call(this);
  86041. this._scene.registerBeforeRender(this._tickCallback);
  86042. };
  86043. /**
  86044. * Disables the cortex.
  86045. */
  86046. PhysicsUpdraftEvent.prototype.disable = function () {
  86047. this._scene.unregisterBeforeRender(this._tickCallback);
  86048. };
  86049. /**
  86050. * Disposes the sphere.
  86051. * @param {bolean} force
  86052. */
  86053. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86054. var _this = this;
  86055. if (force === void 0) { force = true; }
  86056. if (force) {
  86057. this._cylinder.dispose();
  86058. }
  86059. else {
  86060. setTimeout(function () {
  86061. if (!_this._dataFetched) {
  86062. _this._cylinder.dispose();
  86063. }
  86064. }, 0);
  86065. }
  86066. };
  86067. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86068. if (impostor.mass === 0) {
  86069. return null;
  86070. }
  86071. if (!this._intersectsWithCylinder(impostor)) {
  86072. return null;
  86073. }
  86074. var impostorObjectCenter = impostor.getObjectCenter();
  86075. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86076. var direction = this._originDirection;
  86077. }
  86078. else {
  86079. var direction = impostorObjectCenter.subtract(this._originTop);
  86080. }
  86081. var multiplier = this._strength * -1;
  86082. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86083. return { force: force, contactPoint: impostorObjectCenter };
  86084. };
  86085. PhysicsUpdraftEvent.prototype._tick = function () {
  86086. var _this = this;
  86087. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86088. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86089. if (!impostorForceAndContactPoint) {
  86090. return;
  86091. }
  86092. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86093. });
  86094. };
  86095. /*** Helpers ***/
  86096. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86097. if (!this._cylinder) {
  86098. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86099. height: this._height,
  86100. diameter: this._radius * 2,
  86101. }, this._scene);
  86102. this._cylinder.isVisible = false;
  86103. }
  86104. };
  86105. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86106. var impostorObject = impostor.object;
  86107. this._prepareCylinder();
  86108. this._cylinder.position = this._cylinderPosition;
  86109. return this._cylinder.intersectsMesh(impostorObject, true);
  86110. };
  86111. return PhysicsUpdraftEvent;
  86112. }());
  86113. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86114. /***** Vortex *****/
  86115. var PhysicsVortexEvent = /** @class */ (function () {
  86116. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86117. this._scene = _scene;
  86118. this._origin = _origin;
  86119. this._radius = _radius;
  86120. this._strength = _strength;
  86121. this._height = _height;
  86122. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86123. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86124. this._updraftMultiplier = 0.02;
  86125. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86126. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86127. this._physicsEngine = this._scene.getPhysicsEngine();
  86128. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86129. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86130. this._tickCallback = this._tick.bind(this);
  86131. }
  86132. /**
  86133. * Returns the data related to the vortex event (cylinder).
  86134. * @returns {PhysicsVortexEventData}
  86135. */
  86136. PhysicsVortexEvent.prototype.getData = function () {
  86137. this._dataFetched = true;
  86138. return {
  86139. cylinder: this._cylinder,
  86140. };
  86141. };
  86142. /**
  86143. * Enables the vortex.
  86144. */
  86145. PhysicsVortexEvent.prototype.enable = function () {
  86146. this._tickCallback.call(this);
  86147. this._scene.registerBeforeRender(this._tickCallback);
  86148. };
  86149. /**
  86150. * Disables the cortex.
  86151. */
  86152. PhysicsVortexEvent.prototype.disable = function () {
  86153. this._scene.unregisterBeforeRender(this._tickCallback);
  86154. };
  86155. /**
  86156. * Disposes the sphere.
  86157. * @param {bolean} force
  86158. */
  86159. PhysicsVortexEvent.prototype.dispose = function (force) {
  86160. var _this = this;
  86161. if (force === void 0) { force = true; }
  86162. if (force) {
  86163. this._cylinder.dispose();
  86164. }
  86165. else {
  86166. setTimeout(function () {
  86167. if (!_this._dataFetched) {
  86168. _this._cylinder.dispose();
  86169. }
  86170. }, 0);
  86171. }
  86172. };
  86173. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86174. if (impostor.mass === 0) {
  86175. return null;
  86176. }
  86177. if (!this._intersectsWithCylinder(impostor)) {
  86178. return null;
  86179. }
  86180. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86181. return null;
  86182. }
  86183. var impostorObjectCenter = impostor.getObjectCenter();
  86184. 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)
  86185. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86186. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86187. var hit = ray.intersectsMesh(impostor.object);
  86188. var contactPoint = hit.pickedPoint;
  86189. if (!contactPoint) {
  86190. return null;
  86191. }
  86192. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86193. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86194. var directionToOrigin = contactPoint.normalize();
  86195. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86196. directionToOrigin = directionToOrigin.negate();
  86197. }
  86198. // TODO: find a more physically based solution
  86199. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86200. var forceX = directionToOrigin.x * this._strength / 8;
  86201. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86202. var forceZ = directionToOrigin.z * this._strength / 8;
  86203. }
  86204. else {
  86205. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86206. var forceY = this._originTop.y * this._updraftMultiplier;
  86207. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86208. }
  86209. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86210. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86211. return { force: force, contactPoint: impostorObjectCenter };
  86212. };
  86213. PhysicsVortexEvent.prototype._tick = function () {
  86214. var _this = this;
  86215. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86216. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86217. if (!impostorForceAndContactPoint) {
  86218. return;
  86219. }
  86220. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86221. });
  86222. };
  86223. /*** Helpers ***/
  86224. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86225. if (!this._cylinder) {
  86226. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86227. height: this._height,
  86228. diameter: this._radius * 2,
  86229. }, this._scene);
  86230. this._cylinder.isVisible = false;
  86231. }
  86232. };
  86233. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86234. var impostorObject = impostor.object;
  86235. this._prepareCylinder();
  86236. this._cylinder.position = this._cylinderPosition;
  86237. return this._cylinder.intersectsMesh(impostorObject, true);
  86238. };
  86239. return PhysicsVortexEvent;
  86240. }());
  86241. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86242. /***** Enums *****/
  86243. /**
  86244. * The strenght of the force in correspondence to the distance of the affected object
  86245. */
  86246. var PhysicsRadialImpulseFalloff;
  86247. (function (PhysicsRadialImpulseFalloff) {
  86248. /** Defines that impulse is constant in strength across it's whole radius */
  86249. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86250. /** DEfines that impulse gets weaker if it's further from the origin */
  86251. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86252. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86253. /**
  86254. * The strenght of the force in correspondence to the distance of the affected object
  86255. */
  86256. var PhysicsUpdraftMode;
  86257. (function (PhysicsUpdraftMode) {
  86258. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86259. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86260. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86261. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86262. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86263. })(BABYLON || (BABYLON = {}));
  86264. //# sourceMappingURL=babylon.physicsHelper.js.map
  86265. var BABYLON;
  86266. (function (BABYLON) {
  86267. var CannonJSPlugin = /** @class */ (function () {
  86268. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86269. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86270. if (iterations === void 0) { iterations = 10; }
  86271. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86272. this.name = "CannonJSPlugin";
  86273. this._physicsMaterials = new Array();
  86274. this._fixedTimeStep = 1 / 60;
  86275. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86276. this.BJSCANNON = CANNON;
  86277. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86278. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86279. this._tmpPosition = BABYLON.Vector3.Zero();
  86280. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86281. this._tmpUnityRotation = new BABYLON.Quaternion();
  86282. if (!this.isSupported()) {
  86283. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86284. return;
  86285. }
  86286. this._extendNamespace();
  86287. this.world = new this.BJSCANNON.World();
  86288. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86289. this.world.solver.iterations = iterations;
  86290. }
  86291. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86292. this.world.gravity.copy(gravity);
  86293. };
  86294. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86295. this._fixedTimeStep = timeStep;
  86296. };
  86297. CannonJSPlugin.prototype.getTimeStep = function () {
  86298. return this._fixedTimeStep;
  86299. };
  86300. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86301. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86302. };
  86303. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86304. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86305. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86306. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86307. };
  86308. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86309. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86310. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86311. impostor.physicsBody.applyForce(impulse, worldPoint);
  86312. };
  86313. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86314. //parent-child relationship. Does this impostor has a parent impostor?
  86315. if (impostor.parent) {
  86316. if (impostor.physicsBody) {
  86317. this.removePhysicsBody(impostor);
  86318. //TODO is that needed?
  86319. impostor.forceUpdate();
  86320. }
  86321. return;
  86322. }
  86323. //should a new body be created for this impostor?
  86324. if (impostor.isBodyInitRequired()) {
  86325. var shape = this._createShape(impostor);
  86326. //unregister events, if body is being changed
  86327. var oldBody = impostor.physicsBody;
  86328. if (oldBody) {
  86329. this.removePhysicsBody(impostor);
  86330. }
  86331. //create the body and material
  86332. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86333. var bodyCreationObject = {
  86334. mass: impostor.getParam("mass"),
  86335. material: material
  86336. };
  86337. // A simple extend, in case native options were used.
  86338. var nativeOptions = impostor.getParam("nativeOptions");
  86339. for (var key in nativeOptions) {
  86340. if (nativeOptions.hasOwnProperty(key)) {
  86341. bodyCreationObject[key] = nativeOptions[key];
  86342. }
  86343. }
  86344. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86345. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86346. this.world.addEventListener("preStep", impostor.beforeStep);
  86347. this.world.addEventListener("postStep", impostor.afterStep);
  86348. impostor.physicsBody.addShape(shape);
  86349. this.world.add(impostor.physicsBody);
  86350. //try to keep the body moving in the right direction by taking old properties.
  86351. //Should be tested!
  86352. if (oldBody) {
  86353. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86354. impostor.physicsBody[param].copy(oldBody[param]);
  86355. });
  86356. }
  86357. this._processChildMeshes(impostor);
  86358. }
  86359. //now update the body's transformation
  86360. this._updatePhysicsBodyTransformation(impostor);
  86361. };
  86362. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86363. var _this = this;
  86364. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86365. var currentRotation = mainImpostor.object.rotationQuaternion;
  86366. if (meshChildren.length) {
  86367. var processMesh = function (localPosition, mesh) {
  86368. if (!currentRotation || !mesh.rotationQuaternion) {
  86369. return;
  86370. }
  86371. var childImpostor = mesh.getPhysicsImpostor();
  86372. if (childImpostor) {
  86373. var parent = childImpostor.parent;
  86374. if (parent !== mainImpostor) {
  86375. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86376. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86377. if (childImpostor.physicsBody) {
  86378. _this.removePhysicsBody(childImpostor);
  86379. childImpostor.physicsBody = null;
  86380. }
  86381. childImpostor.parent = mainImpostor;
  86382. childImpostor.resetUpdateFlags();
  86383. 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));
  86384. //Add the mass of the children.
  86385. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86386. }
  86387. }
  86388. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86389. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86390. };
  86391. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86392. }
  86393. };
  86394. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86395. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86396. this.world.removeEventListener("preStep", impostor.beforeStep);
  86397. this.world.removeEventListener("postStep", impostor.afterStep);
  86398. this.world.remove(impostor.physicsBody);
  86399. };
  86400. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86401. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86402. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86403. if (!mainBody || !connectedBody) {
  86404. return;
  86405. }
  86406. var constraint;
  86407. var jointData = impostorJoint.joint.jointData;
  86408. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86409. var constraintData = {
  86410. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86411. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86412. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86413. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86414. maxForce: jointData.nativeParams.maxForce,
  86415. collideConnected: !!jointData.collision
  86416. };
  86417. switch (impostorJoint.joint.type) {
  86418. case BABYLON.PhysicsJoint.HingeJoint:
  86419. case BABYLON.PhysicsJoint.Hinge2Joint:
  86420. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86421. break;
  86422. case BABYLON.PhysicsJoint.DistanceJoint:
  86423. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86424. break;
  86425. case BABYLON.PhysicsJoint.SpringJoint:
  86426. var springData = jointData;
  86427. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86428. restLength: springData.length,
  86429. stiffness: springData.stiffness,
  86430. damping: springData.damping,
  86431. localAnchorA: constraintData.pivotA,
  86432. localAnchorB: constraintData.pivotB
  86433. });
  86434. break;
  86435. case BABYLON.PhysicsJoint.LockJoint:
  86436. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86437. break;
  86438. case BABYLON.PhysicsJoint.PointToPointJoint:
  86439. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86440. default:
  86441. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86442. break;
  86443. }
  86444. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86445. constraint.collideConnected = !!jointData.collision;
  86446. impostorJoint.joint.physicsJoint = constraint;
  86447. //don't add spring as constraint, as it is not one.
  86448. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86449. this.world.addConstraint(constraint);
  86450. }
  86451. else {
  86452. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86453. constraint.applyForce();
  86454. });
  86455. }
  86456. };
  86457. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86458. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86459. };
  86460. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86461. var index;
  86462. var mat;
  86463. for (index = 0; index < this._physicsMaterials.length; index++) {
  86464. mat = this._physicsMaterials[index];
  86465. if (mat.friction === friction && mat.restitution === restitution) {
  86466. return mat;
  86467. }
  86468. }
  86469. var currentMat = new this.BJSCANNON.Material(name);
  86470. currentMat.friction = friction;
  86471. currentMat.restitution = restitution;
  86472. this._physicsMaterials.push(currentMat);
  86473. return currentMat;
  86474. };
  86475. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86476. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86477. };
  86478. CannonJSPlugin.prototype._createShape = function (impostor) {
  86479. var object = impostor.object;
  86480. var returnValue;
  86481. var extendSize = impostor.getObjectExtendSize();
  86482. switch (impostor.type) {
  86483. case BABYLON.PhysicsImpostor.SphereImpostor:
  86484. var radiusX = extendSize.x;
  86485. var radiusY = extendSize.y;
  86486. var radiusZ = extendSize.z;
  86487. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86488. break;
  86489. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86490. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86491. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86492. break;
  86493. case BABYLON.PhysicsImpostor.BoxImpostor:
  86494. var box = extendSize.scale(0.5);
  86495. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86496. break;
  86497. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86498. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86499. returnValue = new this.BJSCANNON.Plane();
  86500. break;
  86501. case BABYLON.PhysicsImpostor.MeshImpostor:
  86502. // should transform the vertex data to world coordinates!!
  86503. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86504. var rawFaces = object.getIndices ? object.getIndices() : [];
  86505. if (!rawVerts)
  86506. return;
  86507. // get only scale! so the object could transform correctly.
  86508. var oldPosition = object.position.clone();
  86509. var oldRotation = object.rotation && object.rotation.clone();
  86510. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86511. object.position.copyFromFloats(0, 0, 0);
  86512. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86513. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86514. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86515. var transform = object.computeWorldMatrix(true);
  86516. // convert rawVerts to object space
  86517. var temp = new Array();
  86518. var index;
  86519. for (index = 0; index < rawVerts.length; index += 3) {
  86520. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86521. }
  86522. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86523. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86524. //now set back the transformation!
  86525. object.position.copyFrom(oldPosition);
  86526. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86527. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86528. break;
  86529. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86530. var oldPosition2 = object.position.clone();
  86531. var oldRotation2 = object.rotation && object.rotation.clone();
  86532. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86533. object.position.copyFromFloats(0, 0, 0);
  86534. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86535. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86536. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86537. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86538. returnValue = this._createHeightmap(object);
  86539. object.position.copyFrom(oldPosition2);
  86540. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86541. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86542. object.computeWorldMatrix(true);
  86543. break;
  86544. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86545. returnValue = new this.BJSCANNON.Particle();
  86546. break;
  86547. }
  86548. return returnValue;
  86549. };
  86550. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86551. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86552. var transform = object.computeWorldMatrix(true);
  86553. // convert rawVerts to object space
  86554. var temp = new Array();
  86555. var index;
  86556. for (index = 0; index < pos.length; index += 3) {
  86557. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86558. }
  86559. pos = temp;
  86560. var matrix = new Array();
  86561. //For now pointDepth will not be used and will be automatically calculated.
  86562. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86563. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86564. var boundingInfo = object.getBoundingInfo();
  86565. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86566. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86567. var elementSize = dim * 2 / arraySize;
  86568. for (var i = 0; i < pos.length; i = i + 3) {
  86569. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86570. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86571. var y = -pos[i + 2] + minY;
  86572. if (!matrix[x]) {
  86573. matrix[x] = [];
  86574. }
  86575. if (!matrix[x][z]) {
  86576. matrix[x][z] = y;
  86577. }
  86578. matrix[x][z] = Math.max(y, matrix[x][z]);
  86579. }
  86580. for (var x = 0; x <= arraySize; ++x) {
  86581. if (!matrix[x]) {
  86582. var loc = 1;
  86583. while (!matrix[(x + loc) % arraySize]) {
  86584. loc++;
  86585. }
  86586. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86587. //console.log("missing x", x);
  86588. }
  86589. for (var z = 0; z <= arraySize; ++z) {
  86590. if (!matrix[x][z]) {
  86591. var loc = 1;
  86592. var newValue;
  86593. while (newValue === undefined) {
  86594. newValue = matrix[x][(z + loc++) % arraySize];
  86595. }
  86596. matrix[x][z] = newValue;
  86597. }
  86598. }
  86599. }
  86600. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86601. elementSize: elementSize
  86602. });
  86603. //For future reference, needed for body transformation
  86604. shape.minY = minY;
  86605. return shape;
  86606. };
  86607. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86608. var object = impostor.object;
  86609. //make sure it is updated...
  86610. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86611. // The delta between the mesh position and the mesh bounding box center
  86612. var bInfo = object.getBoundingInfo();
  86613. if (!bInfo)
  86614. return;
  86615. var center = impostor.getObjectCenter();
  86616. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86617. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86618. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86619. this._tmpPosition.copyFrom(center);
  86620. var quaternion = object.rotationQuaternion;
  86621. if (!quaternion) {
  86622. return;
  86623. }
  86624. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86625. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86626. //-90 DEG in X, precalculated
  86627. quaternion = quaternion.multiply(this._minus90X);
  86628. //Invert! (Precalculated, 90 deg in X)
  86629. //No need to clone. this will never change.
  86630. impostor.setDeltaRotation(this._plus90X);
  86631. }
  86632. //If it is a heightfield, if should be centered.
  86633. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86634. var mesh = object;
  86635. var boundingInfo = mesh.getBoundingInfo();
  86636. //calculate the correct body position:
  86637. var rotationQuaternion = mesh.rotationQuaternion;
  86638. mesh.rotationQuaternion = this._tmpUnityRotation;
  86639. mesh.computeWorldMatrix(true);
  86640. //get original center with no rotation
  86641. var c = center.clone();
  86642. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86643. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86644. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86645. mesh.setPreTransformMatrix(p);
  86646. mesh.computeWorldMatrix(true);
  86647. //calculate the translation
  86648. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86649. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86650. //add it inverted to the delta
  86651. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86652. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86653. //rotation is back
  86654. mesh.rotationQuaternion = rotationQuaternion;
  86655. mesh.setPreTransformMatrix(oldPivot);
  86656. mesh.computeWorldMatrix(true);
  86657. }
  86658. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86659. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86660. //this._tmpPosition.copyFrom(object.position);
  86661. }
  86662. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86663. //Now update the impostor object
  86664. impostor.physicsBody.position.copy(this._tmpPosition);
  86665. impostor.physicsBody.quaternion.copy(quaternion);
  86666. };
  86667. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86668. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86669. if (impostor.object.rotationQuaternion) {
  86670. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86671. }
  86672. };
  86673. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86674. impostor.physicsBody.position.copy(newPosition);
  86675. impostor.physicsBody.quaternion.copy(newRotation);
  86676. };
  86677. CannonJSPlugin.prototype.isSupported = function () {
  86678. return this.BJSCANNON !== undefined;
  86679. };
  86680. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86681. impostor.physicsBody.velocity.copy(velocity);
  86682. };
  86683. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86684. impostor.physicsBody.angularVelocity.copy(velocity);
  86685. };
  86686. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86687. var v = impostor.physicsBody.velocity;
  86688. if (!v) {
  86689. return null;
  86690. }
  86691. return new BABYLON.Vector3(v.x, v.y, v.z);
  86692. };
  86693. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86694. var v = impostor.physicsBody.angularVelocity;
  86695. if (!v) {
  86696. return null;
  86697. }
  86698. return new BABYLON.Vector3(v.x, v.y, v.z);
  86699. };
  86700. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86701. impostor.physicsBody.mass = mass;
  86702. impostor.physicsBody.updateMassProperties();
  86703. };
  86704. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86705. return impostor.physicsBody.mass;
  86706. };
  86707. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86708. return impostor.physicsBody.material.friction;
  86709. };
  86710. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86711. impostor.physicsBody.material.friction = friction;
  86712. };
  86713. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86714. return impostor.physicsBody.material.restitution;
  86715. };
  86716. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86717. impostor.physicsBody.material.restitution = restitution;
  86718. };
  86719. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86720. impostor.physicsBody.sleep();
  86721. };
  86722. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86723. impostor.physicsBody.wakeUp();
  86724. };
  86725. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86726. joint.physicsJoint.distance = maxDistance;
  86727. };
  86728. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86729. // if (!motorIndex) {
  86730. // joint.physicsJoint.enableMotor();
  86731. // }
  86732. // }
  86733. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86734. // if (!motorIndex) {
  86735. // joint.physicsJoint.disableMotor();
  86736. // }
  86737. // }
  86738. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86739. if (!motorIndex) {
  86740. joint.physicsJoint.enableMotor();
  86741. joint.physicsJoint.setMotorSpeed(speed);
  86742. if (maxForce) {
  86743. this.setLimit(joint, maxForce);
  86744. }
  86745. }
  86746. };
  86747. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86748. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86749. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86750. };
  86751. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86752. var body = impostor.physicsBody;
  86753. mesh.position.x = body.position.x;
  86754. mesh.position.y = body.position.y;
  86755. mesh.position.z = body.position.z;
  86756. if (mesh.rotationQuaternion) {
  86757. mesh.rotationQuaternion.x = body.quaternion.x;
  86758. mesh.rotationQuaternion.y = body.quaternion.y;
  86759. mesh.rotationQuaternion.z = body.quaternion.z;
  86760. mesh.rotationQuaternion.w = body.quaternion.w;
  86761. }
  86762. };
  86763. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86764. var shape = impostor.physicsBody.shapes[0];
  86765. return shape.boundingSphereRadius;
  86766. };
  86767. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86768. var shape = impostor.physicsBody.shapes[0];
  86769. result.x = shape.halfExtents.x * 2;
  86770. result.y = shape.halfExtents.y * 2;
  86771. result.z = shape.halfExtents.z * 2;
  86772. };
  86773. CannonJSPlugin.prototype.dispose = function () {
  86774. };
  86775. CannonJSPlugin.prototype._extendNamespace = function () {
  86776. //this will force cannon to execute at least one step when using interpolation
  86777. var step_tmp1 = new this.BJSCANNON.Vec3();
  86778. var Engine = this.BJSCANNON;
  86779. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86780. maxSubSteps = maxSubSteps || 10;
  86781. timeSinceLastCalled = timeSinceLastCalled || 0;
  86782. if (timeSinceLastCalled === 0) {
  86783. this.internalStep(dt);
  86784. this.time += dt;
  86785. }
  86786. else {
  86787. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86788. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86789. var t0 = performance.now();
  86790. for (var i = 0; i !== internalSteps; i++) {
  86791. this.internalStep(dt);
  86792. if (performance.now() - t0 > dt * 1000) {
  86793. break;
  86794. }
  86795. }
  86796. this.time += timeSinceLastCalled;
  86797. var h = this.time % dt;
  86798. var h_div_dt = h / dt;
  86799. var interpvelo = step_tmp1;
  86800. var bodies = this.bodies;
  86801. for (var j = 0; j !== bodies.length; j++) {
  86802. var b = bodies[j];
  86803. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86804. b.position.vsub(b.previousPosition, interpvelo);
  86805. interpvelo.scale(h_div_dt, interpvelo);
  86806. b.position.vadd(interpvelo, b.interpolatedPosition);
  86807. }
  86808. else {
  86809. b.interpolatedPosition.copy(b.position);
  86810. b.interpolatedQuaternion.copy(b.quaternion);
  86811. }
  86812. }
  86813. }
  86814. };
  86815. };
  86816. return CannonJSPlugin;
  86817. }());
  86818. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86819. })(BABYLON || (BABYLON = {}));
  86820. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86821. var BABYLON;
  86822. (function (BABYLON) {
  86823. var OimoJSPlugin = /** @class */ (function () {
  86824. function OimoJSPlugin(iterations) {
  86825. this.name = "OimoJSPlugin";
  86826. this._tmpImpostorsArray = [];
  86827. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86828. this.BJSOIMO = OIMO;
  86829. this.world = new this.BJSOIMO.World({
  86830. iterations: iterations
  86831. });
  86832. this.world.clear();
  86833. }
  86834. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86835. this.world.gravity.copy(gravity);
  86836. };
  86837. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86838. this.world.timeStep = timeStep;
  86839. };
  86840. OimoJSPlugin.prototype.getTimeStep = function () {
  86841. return this.world.timeStep;
  86842. };
  86843. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86844. var _this = this;
  86845. impostors.forEach(function (impostor) {
  86846. impostor.beforeStep();
  86847. });
  86848. this.world.step();
  86849. impostors.forEach(function (impostor) {
  86850. impostor.afterStep();
  86851. //update the ordered impostors array
  86852. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86853. });
  86854. //check for collisions
  86855. var contact = this.world.contacts;
  86856. while (contact !== null) {
  86857. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86858. contact = contact.next;
  86859. continue;
  86860. }
  86861. //is this body colliding with any other? get the impostor
  86862. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86863. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86864. if (!mainImpostor || !collidingImpostor) {
  86865. contact = contact.next;
  86866. continue;
  86867. }
  86868. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86869. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86870. contact = contact.next;
  86871. }
  86872. };
  86873. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86874. var mass = impostor.physicsBody.mass;
  86875. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86876. };
  86877. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86878. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86879. this.applyImpulse(impostor, force, contactPoint);
  86880. };
  86881. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86882. var _this = this;
  86883. //parent-child relationship. Does this impostor has a parent impostor?
  86884. if (impostor.parent) {
  86885. if (impostor.physicsBody) {
  86886. this.removePhysicsBody(impostor);
  86887. //TODO is that needed?
  86888. impostor.forceUpdate();
  86889. }
  86890. return;
  86891. }
  86892. if (impostor.isBodyInitRequired()) {
  86893. var bodyConfig = {
  86894. name: impostor.uniqueId,
  86895. //Oimo must have mass, also for static objects.
  86896. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86897. size: [],
  86898. type: [],
  86899. pos: [],
  86900. posShape: [],
  86901. rot: [],
  86902. rotShape: [],
  86903. move: impostor.getParam("mass") !== 0,
  86904. density: impostor.getParam("mass"),
  86905. friction: impostor.getParam("friction"),
  86906. restitution: impostor.getParam("restitution"),
  86907. //Supporting older versions of Oimo
  86908. world: this.world
  86909. };
  86910. var impostors = [impostor];
  86911. var addToArray = function (parent) {
  86912. if (!parent.getChildMeshes)
  86913. return;
  86914. parent.getChildMeshes().forEach(function (m) {
  86915. if (m.physicsImpostor) {
  86916. impostors.push(m.physicsImpostor);
  86917. //m.physicsImpostor._init();
  86918. }
  86919. });
  86920. };
  86921. addToArray(impostor.object);
  86922. var checkWithEpsilon_1 = function (value) {
  86923. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86924. };
  86925. var globalQuaternion_1 = new BABYLON.Quaternion();
  86926. impostors.forEach(function (i) {
  86927. if (!i.object.rotationQuaternion) {
  86928. return;
  86929. }
  86930. //get the correct bounding box
  86931. var oldQuaternion = i.object.rotationQuaternion;
  86932. globalQuaternion_1 = oldQuaternion.clone();
  86933. var rot = oldQuaternion.toEulerAngles();
  86934. var extendSize = i.getObjectExtendSize();
  86935. var radToDeg = 57.295779513082320876;
  86936. if (i === impostor) {
  86937. var center = impostor.getObjectCenter();
  86938. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86939. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86940. //Can also use Array.prototype.push.apply
  86941. bodyConfig.pos.push(center.x);
  86942. bodyConfig.pos.push(center.y);
  86943. bodyConfig.pos.push(center.z);
  86944. bodyConfig.posShape.push(0, 0, 0);
  86945. //tmp solution
  86946. bodyConfig.rot.push(0);
  86947. bodyConfig.rot.push(0);
  86948. bodyConfig.rot.push(0);
  86949. bodyConfig.rotShape.push(0, 0, 0);
  86950. }
  86951. else {
  86952. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86953. bodyConfig.posShape.push(localPosition.x);
  86954. bodyConfig.posShape.push(localPosition.y);
  86955. bodyConfig.posShape.push(localPosition.z);
  86956. bodyConfig.pos.push(0, 0, 0);
  86957. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86958. bodyConfig.rot.push(0);
  86959. bodyConfig.rot.push(0);
  86960. bodyConfig.rot.push(0);
  86961. bodyConfig.rotShape.push(rot.x * radToDeg);
  86962. bodyConfig.rotShape.push(rot.y * radToDeg);
  86963. bodyConfig.rotShape.push(rot.z * radToDeg);
  86964. }
  86965. // register mesh
  86966. switch (i.type) {
  86967. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86968. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86969. case BABYLON.PhysicsImpostor.SphereImpostor:
  86970. var radiusX = extendSize.x;
  86971. var radiusY = extendSize.y;
  86972. var radiusZ = extendSize.z;
  86973. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86974. bodyConfig.type.push('sphere');
  86975. //due to the way oimo works with compounds, add 3 times
  86976. bodyConfig.size.push(size);
  86977. bodyConfig.size.push(size);
  86978. bodyConfig.size.push(size);
  86979. break;
  86980. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86981. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86982. var sizeY = checkWithEpsilon_1(extendSize.y);
  86983. bodyConfig.type.push('cylinder');
  86984. bodyConfig.size.push(sizeX);
  86985. bodyConfig.size.push(sizeY);
  86986. //due to the way oimo works with compounds, add one more value.
  86987. bodyConfig.size.push(sizeY);
  86988. break;
  86989. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86990. case BABYLON.PhysicsImpostor.BoxImpostor:
  86991. default:
  86992. var sizeX = checkWithEpsilon_1(extendSize.x);
  86993. var sizeY = checkWithEpsilon_1(extendSize.y);
  86994. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86995. bodyConfig.type.push('box');
  86996. //if (i === impostor) {
  86997. bodyConfig.size.push(sizeX);
  86998. bodyConfig.size.push(sizeY);
  86999. bodyConfig.size.push(sizeZ);
  87000. //} else {
  87001. // bodyConfig.size.push(0,0,0);
  87002. //}
  87003. break;
  87004. }
  87005. //actually not needed, but hey...
  87006. i.object.rotationQuaternion = oldQuaternion;
  87007. });
  87008. impostor.physicsBody = this.world.add(bodyConfig);
  87009. // set the quaternion, ignoring the previously defined (euler) rotation
  87010. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  87011. // update with delta 0, so the body will reveive the new rotation.
  87012. impostor.physicsBody.updatePosition(0);
  87013. }
  87014. else {
  87015. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  87016. }
  87017. impostor.setDeltaPosition(this._tmpPositionVector);
  87018. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  87019. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  87020. };
  87021. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87022. //impostor.physicsBody.dispose();
  87023. //Same as : (older oimo versions)
  87024. this.world.removeRigidBody(impostor.physicsBody);
  87025. };
  87026. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87027. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87028. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87029. if (!mainBody || !connectedBody) {
  87030. return;
  87031. }
  87032. var jointData = impostorJoint.joint.jointData;
  87033. var options = jointData.nativeParams || {};
  87034. var type;
  87035. var nativeJointData = {
  87036. body1: mainBody,
  87037. body2: connectedBody,
  87038. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87039. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87040. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87041. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87042. min: options.min,
  87043. max: options.max,
  87044. collision: options.collision || jointData.collision,
  87045. spring: options.spring,
  87046. //supporting older version of Oimo
  87047. world: this.world
  87048. };
  87049. switch (impostorJoint.joint.type) {
  87050. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87051. type = "jointBall";
  87052. break;
  87053. case BABYLON.PhysicsJoint.SpringJoint:
  87054. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87055. var springData = jointData;
  87056. nativeJointData.min = springData.length || nativeJointData.min;
  87057. //Max should also be set, just make sure it is at least min
  87058. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87059. case BABYLON.PhysicsJoint.DistanceJoint:
  87060. type = "jointDistance";
  87061. nativeJointData.max = jointData.maxDistance;
  87062. break;
  87063. case BABYLON.PhysicsJoint.PrismaticJoint:
  87064. type = "jointPrisme";
  87065. break;
  87066. case BABYLON.PhysicsJoint.SliderJoint:
  87067. type = "jointSlide";
  87068. break;
  87069. case BABYLON.PhysicsJoint.WheelJoint:
  87070. type = "jointWheel";
  87071. break;
  87072. case BABYLON.PhysicsJoint.HingeJoint:
  87073. default:
  87074. type = "jointHinge";
  87075. break;
  87076. }
  87077. nativeJointData.type = type;
  87078. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87079. };
  87080. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87081. //Bug in Oimo prevents us from disposing a joint in the playground
  87082. //joint.joint.physicsJoint.dispose();
  87083. //So we will bruteforce it!
  87084. try {
  87085. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87086. }
  87087. catch (e) {
  87088. BABYLON.Tools.Warn(e);
  87089. }
  87090. };
  87091. OimoJSPlugin.prototype.isSupported = function () {
  87092. return this.BJSOIMO !== undefined;
  87093. };
  87094. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87095. if (!impostor.physicsBody.sleeping) {
  87096. //TODO check that
  87097. /*if (impostor.physicsBody.shapes.next) {
  87098. var parentShape = this._getLastShape(impostor.physicsBody);
  87099. impostor.object.position.copyFrom(parentShape.position);
  87100. console.log(parentShape.position);
  87101. } else {*/
  87102. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87103. //}
  87104. if (impostor.object.rotationQuaternion) {
  87105. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87106. }
  87107. }
  87108. };
  87109. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87110. var body = impostor.physicsBody;
  87111. body.position.copy(newPosition);
  87112. body.orientation.copy(newRotation);
  87113. body.syncShapes();
  87114. body.awake();
  87115. };
  87116. /*private _getLastShape(body: any): any {
  87117. var lastShape = body.shapes;
  87118. while (lastShape.next) {
  87119. lastShape = lastShape.next;
  87120. }
  87121. return lastShape;
  87122. }*/
  87123. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87124. impostor.physicsBody.linearVelocity.copy(velocity);
  87125. };
  87126. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87127. impostor.physicsBody.angularVelocity.copy(velocity);
  87128. };
  87129. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87130. var v = impostor.physicsBody.linearVelocity;
  87131. if (!v) {
  87132. return null;
  87133. }
  87134. return new BABYLON.Vector3(v.x, v.y, v.z);
  87135. };
  87136. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87137. var v = impostor.physicsBody.angularVelocity;
  87138. if (!v) {
  87139. return null;
  87140. }
  87141. return new BABYLON.Vector3(v.x, v.y, v.z);
  87142. };
  87143. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87144. var staticBody = mass === 0;
  87145. //this will actually set the body's density and not its mass.
  87146. //But this is how oimo treats the mass variable.
  87147. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87148. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87149. };
  87150. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87151. return impostor.physicsBody.shapes.density;
  87152. };
  87153. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87154. return impostor.physicsBody.shapes.friction;
  87155. };
  87156. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87157. impostor.physicsBody.shapes.friction = friction;
  87158. };
  87159. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87160. return impostor.physicsBody.shapes.restitution;
  87161. };
  87162. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87163. impostor.physicsBody.shapes.restitution = restitution;
  87164. };
  87165. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87166. impostor.physicsBody.sleep();
  87167. };
  87168. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87169. impostor.physicsBody.awake();
  87170. };
  87171. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87172. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87173. if (minDistance !== void 0) {
  87174. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87175. }
  87176. };
  87177. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87178. //TODO separate rotational and transational motors.
  87179. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87180. if (motor) {
  87181. motor.setMotor(speed, maxForce);
  87182. }
  87183. };
  87184. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87185. //TODO separate rotational and transational motors.
  87186. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87187. if (motor) {
  87188. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87189. }
  87190. };
  87191. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87192. var body = impostor.physicsBody;
  87193. mesh.position.x = body.position.x;
  87194. mesh.position.y = body.position.y;
  87195. mesh.position.z = body.position.z;
  87196. if (mesh.rotationQuaternion) {
  87197. mesh.rotationQuaternion.x = body.orientation.x;
  87198. mesh.rotationQuaternion.y = body.orientation.y;
  87199. mesh.rotationQuaternion.z = body.orientation.z;
  87200. mesh.rotationQuaternion.w = body.orientation.s;
  87201. }
  87202. };
  87203. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87204. return impostor.physicsBody.shapes.radius;
  87205. };
  87206. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87207. var shape = impostor.physicsBody.shapes;
  87208. result.x = shape.halfWidth * 2;
  87209. result.y = shape.halfHeight * 2;
  87210. result.z = shape.halfDepth * 2;
  87211. };
  87212. OimoJSPlugin.prototype.dispose = function () {
  87213. this.world.clear();
  87214. };
  87215. return OimoJSPlugin;
  87216. }());
  87217. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87218. })(BABYLON || (BABYLON = {}));
  87219. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87220. var BABYLON;
  87221. (function (BABYLON) {
  87222. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87223. // All values and structures referenced from:
  87224. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87225. var DDS_MAGIC = 0x20534444;
  87226. var
  87227. //DDSD_CAPS = 0x1,
  87228. //DDSD_HEIGHT = 0x2,
  87229. //DDSD_WIDTH = 0x4,
  87230. //DDSD_PITCH = 0x8,
  87231. //DDSD_PIXELFORMAT = 0x1000,
  87232. DDSD_MIPMAPCOUNT = 0x20000;
  87233. //DDSD_LINEARSIZE = 0x80000,
  87234. //DDSD_DEPTH = 0x800000;
  87235. // var DDSCAPS_COMPLEX = 0x8,
  87236. // DDSCAPS_MIPMAP = 0x400000,
  87237. // DDSCAPS_TEXTURE = 0x1000;
  87238. var DDSCAPS2_CUBEMAP = 0x200;
  87239. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87240. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87241. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87242. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87243. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87244. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87245. // DDSCAPS2_VOLUME = 0x200000;
  87246. var
  87247. //DDPF_ALPHAPIXELS = 0x1,
  87248. //DDPF_ALPHA = 0x2,
  87249. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87250. //DDPF_YUV = 0x200,
  87251. DDPF_LUMINANCE = 0x20000;
  87252. function FourCCToInt32(value) {
  87253. return value.charCodeAt(0) +
  87254. (value.charCodeAt(1) << 8) +
  87255. (value.charCodeAt(2) << 16) +
  87256. (value.charCodeAt(3) << 24);
  87257. }
  87258. function Int32ToFourCC(value) {
  87259. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87260. }
  87261. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87262. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87263. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87264. var FOURCC_DX10 = FourCCToInt32("DX10");
  87265. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87266. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87267. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87268. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87269. var headerLengthInt = 31; // The header length in 32 bit ints
  87270. // Offsets into the header array
  87271. var off_magic = 0;
  87272. var off_size = 1;
  87273. var off_flags = 2;
  87274. var off_height = 3;
  87275. var off_width = 4;
  87276. var off_mipmapCount = 7;
  87277. var off_pfFlags = 20;
  87278. var off_pfFourCC = 21;
  87279. var off_RGBbpp = 22;
  87280. var off_RMask = 23;
  87281. var off_GMask = 24;
  87282. var off_BMask = 25;
  87283. var off_AMask = 26;
  87284. // var off_caps1 = 27;
  87285. var off_caps2 = 28;
  87286. // var off_caps3 = 29;
  87287. // var off_caps4 = 30;
  87288. var off_dxgiFormat = 32;
  87289. ;
  87290. var DDSTools = /** @class */ (function () {
  87291. function DDSTools() {
  87292. }
  87293. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87294. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87295. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87296. var mipmapCount = 1;
  87297. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87298. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87299. }
  87300. var fourCC = header[off_pfFourCC];
  87301. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87302. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87303. switch (fourCC) {
  87304. case FOURCC_D3DFMT_R16G16B16A16F:
  87305. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87306. break;
  87307. case FOURCC_D3DFMT_R32G32B32A32F:
  87308. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87309. break;
  87310. case FOURCC_DX10:
  87311. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87312. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87313. break;
  87314. }
  87315. }
  87316. return {
  87317. width: header[off_width],
  87318. height: header[off_height],
  87319. mipmapCount: mipmapCount,
  87320. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87321. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87322. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87323. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87324. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87325. dxgiFormat: dxgiFormat,
  87326. textureType: textureType
  87327. };
  87328. };
  87329. DDSTools._ToHalfFloat = function (value) {
  87330. if (!DDSTools._FloatView) {
  87331. DDSTools._FloatView = new Float32Array(1);
  87332. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87333. }
  87334. DDSTools._FloatView[0] = value;
  87335. var x = DDSTools._Int32View[0];
  87336. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87337. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87338. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87339. /* If zero, or denormal, or exponent underflows too much for a denormal
  87340. * half, return signed zero. */
  87341. if (e < 103) {
  87342. return bits;
  87343. }
  87344. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87345. if (e > 142) {
  87346. bits |= 0x7c00;
  87347. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87348. * not Inf, so make sure we set one mantissa bit too. */
  87349. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87350. return bits;
  87351. }
  87352. /* If exponent underflows but not too much, return a denormal */
  87353. if (e < 113) {
  87354. m |= 0x0800;
  87355. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87356. * to 1, which is OK. */
  87357. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87358. return bits;
  87359. }
  87360. bits |= ((e - 112) << 10) | (m >> 1);
  87361. bits += m & 1;
  87362. return bits;
  87363. };
  87364. DDSTools._FromHalfFloat = function (value) {
  87365. var s = (value & 0x8000) >> 15;
  87366. var e = (value & 0x7C00) >> 10;
  87367. var f = value & 0x03FF;
  87368. if (e === 0) {
  87369. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87370. }
  87371. else if (e == 0x1F) {
  87372. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87373. }
  87374. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87375. };
  87376. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87377. var destArray = new Float32Array(dataLength);
  87378. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87379. var index = 0;
  87380. for (var y = 0; y < height; y++) {
  87381. for (var x = 0; x < width; x++) {
  87382. var srcPos = (x + y * width) * 4;
  87383. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87384. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87385. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87386. if (DDSTools.StoreLODInAlphaChannel) {
  87387. destArray[index + 3] = lod;
  87388. }
  87389. else {
  87390. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87391. }
  87392. index += 4;
  87393. }
  87394. }
  87395. return destArray;
  87396. };
  87397. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87398. if (DDSTools.StoreLODInAlphaChannel) {
  87399. var destArray = new Uint16Array(dataLength);
  87400. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87401. var index = 0;
  87402. for (var y = 0; y < height; y++) {
  87403. for (var x = 0; x < width; x++) {
  87404. var srcPos = (x + y * width) * 4;
  87405. destArray[index] = srcData[srcPos];
  87406. destArray[index + 1] = srcData[srcPos + 1];
  87407. destArray[index + 2] = srcData[srcPos + 2];
  87408. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87409. index += 4;
  87410. }
  87411. }
  87412. return destArray;
  87413. }
  87414. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87415. };
  87416. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87417. if (DDSTools.StoreLODInAlphaChannel) {
  87418. var destArray = new Float32Array(dataLength);
  87419. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87420. var index = 0;
  87421. for (var y = 0; y < height; y++) {
  87422. for (var x = 0; x < width; x++) {
  87423. var srcPos = (x + y * width) * 4;
  87424. destArray[index] = srcData[srcPos];
  87425. destArray[index + 1] = srcData[srcPos + 1];
  87426. destArray[index + 2] = srcData[srcPos + 2];
  87427. destArray[index + 3] = lod;
  87428. index += 4;
  87429. }
  87430. }
  87431. return destArray;
  87432. }
  87433. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87434. };
  87435. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87436. var destArray = new Uint8Array(dataLength);
  87437. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87438. var index = 0;
  87439. for (var y = 0; y < height; y++) {
  87440. for (var x = 0; x < width; x++) {
  87441. var srcPos = (x + y * width) * 4;
  87442. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87443. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87444. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87445. if (DDSTools.StoreLODInAlphaChannel) {
  87446. destArray[index + 3] = lod;
  87447. }
  87448. else {
  87449. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87450. }
  87451. index += 4;
  87452. }
  87453. }
  87454. return destArray;
  87455. };
  87456. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87457. var destArray = new Uint8Array(dataLength);
  87458. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87459. var index = 0;
  87460. for (var y = 0; y < height; y++) {
  87461. for (var x = 0; x < width; x++) {
  87462. var srcPos = (x + y * width) * 4;
  87463. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87464. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87465. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87466. if (DDSTools.StoreLODInAlphaChannel) {
  87467. destArray[index + 3] = lod;
  87468. }
  87469. else {
  87470. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87471. }
  87472. index += 4;
  87473. }
  87474. }
  87475. return destArray;
  87476. };
  87477. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87478. var byteArray = new Uint8Array(dataLength);
  87479. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87480. var index = 0;
  87481. for (var y = 0; y < height; y++) {
  87482. for (var x = 0; x < width; x++) {
  87483. var srcPos = (x + y * width) * 4;
  87484. byteArray[index] = srcData[srcPos + rOffset];
  87485. byteArray[index + 1] = srcData[srcPos + gOffset];
  87486. byteArray[index + 2] = srcData[srcPos + bOffset];
  87487. byteArray[index + 3] = srcData[srcPos + aOffset];
  87488. index += 4;
  87489. }
  87490. }
  87491. return byteArray;
  87492. };
  87493. DDSTools._ExtractLongWordOrder = function (value) {
  87494. if (value === 0 || value === 255 || value === -16777216) {
  87495. return 0;
  87496. }
  87497. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87498. };
  87499. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87500. var byteArray = new Uint8Array(dataLength);
  87501. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87502. var index = 0;
  87503. for (var y = 0; y < height; y++) {
  87504. for (var x = 0; x < width; x++) {
  87505. var srcPos = (x + y * width) * 3;
  87506. byteArray[index] = srcData[srcPos + rOffset];
  87507. byteArray[index + 1] = srcData[srcPos + gOffset];
  87508. byteArray[index + 2] = srcData[srcPos + bOffset];
  87509. index += 3;
  87510. }
  87511. }
  87512. return byteArray;
  87513. };
  87514. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87515. var byteArray = new Uint8Array(dataLength);
  87516. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87517. var index = 0;
  87518. for (var y = 0; y < height; y++) {
  87519. for (var x = 0; x < width; x++) {
  87520. var srcPos = (x + y * width);
  87521. byteArray[index] = srcData[srcPos];
  87522. index++;
  87523. }
  87524. }
  87525. return byteArray;
  87526. };
  87527. /**
  87528. * Uploads DDS Levels to a Babylon Texture
  87529. * @hidden
  87530. */
  87531. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87532. if (lodIndex === void 0) { lodIndex = -1; }
  87533. var sphericalPolynomialFaces = null;
  87534. if (info.sphericalPolynomial) {
  87535. sphericalPolynomialFaces = new Array();
  87536. }
  87537. var ext = engine.getCaps().s3tc;
  87538. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87539. var fourCC, width, height, dataLength = 0, dataOffset;
  87540. var byteArray, mipmapCount, mip;
  87541. var internalCompressedFormat = 0;
  87542. var blockBytes = 1;
  87543. if (header[off_magic] !== DDS_MAGIC) {
  87544. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87545. return;
  87546. }
  87547. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87548. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87549. return;
  87550. }
  87551. if (info.isCompressed && !ext) {
  87552. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87553. return;
  87554. }
  87555. var bpp = header[off_RGBbpp];
  87556. dataOffset = header[off_size] + 4;
  87557. var computeFormats = false;
  87558. if (info.isFourCC) {
  87559. fourCC = header[off_pfFourCC];
  87560. switch (fourCC) {
  87561. case FOURCC_DXT1:
  87562. blockBytes = 8;
  87563. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87564. break;
  87565. case FOURCC_DXT3:
  87566. blockBytes = 16;
  87567. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87568. break;
  87569. case FOURCC_DXT5:
  87570. blockBytes = 16;
  87571. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87572. break;
  87573. case FOURCC_D3DFMT_R16G16B16A16F:
  87574. computeFormats = true;
  87575. break;
  87576. case FOURCC_D3DFMT_R32G32B32A32F:
  87577. computeFormats = true;
  87578. break;
  87579. case FOURCC_DX10:
  87580. // There is an additionnal header so dataOffset need to be changed
  87581. dataOffset += 5 * 4; // 5 uints
  87582. var supported = false;
  87583. switch (info.dxgiFormat) {
  87584. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87585. computeFormats = true;
  87586. supported = true;
  87587. break;
  87588. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87589. info.isRGB = true;
  87590. info.isFourCC = false;
  87591. bpp = 32;
  87592. supported = true;
  87593. break;
  87594. }
  87595. if (supported) {
  87596. break;
  87597. }
  87598. default:
  87599. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87600. return;
  87601. }
  87602. }
  87603. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87604. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87605. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87606. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87607. if (computeFormats) {
  87608. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87609. }
  87610. mipmapCount = 1;
  87611. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87612. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87613. }
  87614. for (var face = 0; face < faces; face++) {
  87615. width = header[off_width];
  87616. height = header[off_height];
  87617. for (mip = 0; mip < mipmapCount; ++mip) {
  87618. if (lodIndex === -1 || lodIndex === mip) {
  87619. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87620. var i = (lodIndex === -1) ? mip : 0;
  87621. if (!info.isCompressed && info.isFourCC) {
  87622. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87623. dataLength = width * height * 4;
  87624. var floatArray = null;
  87625. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87626. if (bpp === 128) {
  87627. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87628. if (sphericalPolynomialFaces && i == 0) {
  87629. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87630. }
  87631. }
  87632. else if (bpp === 64) {
  87633. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87634. if (sphericalPolynomialFaces && i == 0) {
  87635. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87636. }
  87637. }
  87638. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87639. }
  87640. else {
  87641. if (bpp === 128) {
  87642. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87643. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87644. if (sphericalPolynomialFaces && i == 0) {
  87645. sphericalPolynomialFaces.push(floatArray);
  87646. }
  87647. }
  87648. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87649. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87650. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87651. if (sphericalPolynomialFaces && i == 0) {
  87652. sphericalPolynomialFaces.push(floatArray);
  87653. }
  87654. }
  87655. else { // 64
  87656. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87657. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87658. if (sphericalPolynomialFaces && i == 0) {
  87659. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87660. }
  87661. }
  87662. }
  87663. if (floatArray) {
  87664. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  87665. }
  87666. }
  87667. else if (info.isRGB) {
  87668. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87669. if (bpp === 24) {
  87670. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  87671. dataLength = width * height * 3;
  87672. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87673. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87674. }
  87675. else { // 32
  87676. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87677. dataLength = width * height * 4;
  87678. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87679. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87680. }
  87681. }
  87682. else if (info.isLuminance) {
  87683. var unpackAlignment = engine._getUnpackAlignement();
  87684. var unpaddedRowSize = width;
  87685. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87686. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87687. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87688. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  87689. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87690. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87691. }
  87692. else {
  87693. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87694. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87695. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87696. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  87697. }
  87698. }
  87699. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87700. width *= 0.5;
  87701. height *= 0.5;
  87702. width = Math.max(1.0, width);
  87703. height = Math.max(1.0, height);
  87704. }
  87705. if (currentFace !== undefined) {
  87706. // Loading a single face
  87707. break;
  87708. }
  87709. }
  87710. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87711. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87712. size: header[off_width],
  87713. right: sphericalPolynomialFaces[0],
  87714. left: sphericalPolynomialFaces[1],
  87715. up: sphericalPolynomialFaces[2],
  87716. down: sphericalPolynomialFaces[3],
  87717. front: sphericalPolynomialFaces[4],
  87718. back: sphericalPolynomialFaces[5],
  87719. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87720. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87721. gammaSpace: false,
  87722. });
  87723. }
  87724. else {
  87725. info.sphericalPolynomial = undefined;
  87726. }
  87727. };
  87728. DDSTools.StoreLODInAlphaChannel = false;
  87729. return DDSTools;
  87730. }());
  87731. BABYLON.DDSTools = DDSTools;
  87732. })(BABYLON || (BABYLON = {}));
  87733. //# sourceMappingURL=babylon.dds.js.map
  87734. var BABYLON;
  87735. (function (BABYLON) {
  87736. /**
  87737. * Implementation of the DDS Texture Loader.
  87738. */
  87739. var DDSTextureLoader = /** @class */ (function () {
  87740. function DDSTextureLoader() {
  87741. /**
  87742. * Defines wether the loader supports cascade loading the different faces.
  87743. */
  87744. this.supportCascades = true;
  87745. }
  87746. /**
  87747. * This returns if the loader support the current file information.
  87748. * @param extension defines the file extension of the file being loaded
  87749. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87750. * @param fallback defines the fallback internal texture if any
  87751. * @param isBase64 defines whether the texture is encoded as a base64
  87752. * @param isBuffer defines whether the texture data are stored as a buffer
  87753. * @returns true if the loader can load the specified file
  87754. */
  87755. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  87756. return extension.indexOf(".dds") === 0;
  87757. };
  87758. /**
  87759. * Transform the url before loading if required.
  87760. * @param rootUrl the url of the texture
  87761. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87762. * @returns the transformed texture
  87763. */
  87764. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  87765. return rootUrl;
  87766. };
  87767. /**
  87768. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  87769. * @param rootUrl the url of the texture
  87770. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87771. * @returns the fallback texture
  87772. */
  87773. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  87774. return null;
  87775. };
  87776. /**
  87777. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  87778. * @param data contains the texture data
  87779. * @param texture defines the BabylonJS internal texture
  87780. * @param createPolynomials will be true if polynomials have been requested
  87781. * @param onLoad defines the callback to trigger once the texture is ready
  87782. * @param onError defines the callback to trigger in case of error
  87783. */
  87784. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  87785. var engine = texture.getEngine();
  87786. var info;
  87787. var loadMipmap = false;
  87788. if (Array.isArray(imgs)) {
  87789. for (var index = 0; index < imgs.length; index++) {
  87790. var data_1 = imgs[index];
  87791. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  87792. texture.width = info.width;
  87793. texture.height = info.height;
  87794. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87795. engine._unpackFlipY(info.isCompressed);
  87796. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  87797. if (!info.isFourCC && info.mipmapCount === 1) {
  87798. engine.generateMipMapsForCubemap(texture);
  87799. }
  87800. }
  87801. }
  87802. else {
  87803. var data = imgs;
  87804. info = BABYLON.DDSTools.GetDDSInfo(data);
  87805. texture.width = info.width;
  87806. texture.height = info.height;
  87807. if (createPolynomials) {
  87808. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  87809. }
  87810. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87811. engine._unpackFlipY(info.isCompressed);
  87812. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  87813. if (!info.isFourCC && info.mipmapCount === 1) {
  87814. engine.generateMipMapsForCubemap(texture);
  87815. }
  87816. }
  87817. engine._setCubeMapTextureParams(loadMipmap);
  87818. texture.isReady = true;
  87819. if (onLoad) {
  87820. onLoad({ isDDS: true, width: texture.width, info: info, imgs: imgs, texture: texture });
  87821. }
  87822. };
  87823. /**
  87824. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  87825. * @param data contains the texture data
  87826. * @param texture defines the BabylonJS internal texture
  87827. * @param callback defines the method to call once ready to upload
  87828. */
  87829. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  87830. var info = BABYLON.DDSTools.GetDDSInfo(data);
  87831. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  87832. callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {
  87833. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  87834. });
  87835. };
  87836. return DDSTextureLoader;
  87837. }());
  87838. // Register the loader.
  87839. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  87840. })(BABYLON || (BABYLON = {}));
  87841. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  87842. var BABYLON;
  87843. (function (BABYLON) {
  87844. /*
  87845. * Based on jsTGALoader - Javascript loader for TGA file
  87846. * By Vincent Thibault
  87847. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87848. */
  87849. var TGATools = /** @class */ (function () {
  87850. function TGATools() {
  87851. }
  87852. TGATools.GetTGAHeader = function (data) {
  87853. var offset = 0;
  87854. var header = {
  87855. id_length: data[offset++],
  87856. colormap_type: data[offset++],
  87857. image_type: data[offset++],
  87858. colormap_index: data[offset++] | data[offset++] << 8,
  87859. colormap_length: data[offset++] | data[offset++] << 8,
  87860. colormap_size: data[offset++],
  87861. origin: [
  87862. data[offset++] | data[offset++] << 8,
  87863. data[offset++] | data[offset++] << 8
  87864. ],
  87865. width: data[offset++] | data[offset++] << 8,
  87866. height: data[offset++] | data[offset++] << 8,
  87867. pixel_size: data[offset++],
  87868. flags: data[offset++]
  87869. };
  87870. return header;
  87871. };
  87872. /**
  87873. * Uploads TGA content to a Babylon Texture
  87874. * @hidden
  87875. */
  87876. TGATools.UploadContent = function (texture, data) {
  87877. // Not enough data to contain header ?
  87878. if (data.length < 19) {
  87879. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87880. return;
  87881. }
  87882. // Read Header
  87883. var offset = 18;
  87884. var header = TGATools.GetTGAHeader(data);
  87885. // Assume it's a valid Targa file.
  87886. if (header.id_length + offset > data.length) {
  87887. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87888. return;
  87889. }
  87890. // Skip not needed data
  87891. offset += header.id_length;
  87892. var use_rle = false;
  87893. var use_pal = false;
  87894. var use_grey = false;
  87895. // Get some informations.
  87896. switch (header.image_type) {
  87897. case TGATools._TYPE_RLE_INDEXED:
  87898. use_rle = true;
  87899. case TGATools._TYPE_INDEXED:
  87900. use_pal = true;
  87901. break;
  87902. case TGATools._TYPE_RLE_RGB:
  87903. use_rle = true;
  87904. case TGATools._TYPE_RGB:
  87905. // use_rgb = true;
  87906. break;
  87907. case TGATools._TYPE_RLE_GREY:
  87908. use_rle = true;
  87909. case TGATools._TYPE_GREY:
  87910. use_grey = true;
  87911. break;
  87912. }
  87913. var pixel_data;
  87914. // var numAlphaBits = header.flags & 0xf;
  87915. var pixel_size = header.pixel_size >> 3;
  87916. var pixel_total = header.width * header.height * pixel_size;
  87917. // Read palettes
  87918. var palettes;
  87919. if (use_pal) {
  87920. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87921. }
  87922. // Read LRE
  87923. if (use_rle) {
  87924. pixel_data = new Uint8Array(pixel_total);
  87925. var c, count, i;
  87926. var localOffset = 0;
  87927. var pixels = new Uint8Array(pixel_size);
  87928. while (offset < pixel_total && localOffset < pixel_total) {
  87929. c = data[offset++];
  87930. count = (c & 0x7f) + 1;
  87931. // RLE pixels
  87932. if (c & 0x80) {
  87933. // Bind pixel tmp array
  87934. for (i = 0; i < pixel_size; ++i) {
  87935. pixels[i] = data[offset++];
  87936. }
  87937. // Copy pixel array
  87938. for (i = 0; i < count; ++i) {
  87939. pixel_data.set(pixels, localOffset + i * pixel_size);
  87940. }
  87941. localOffset += pixel_size * count;
  87942. }
  87943. // Raw pixels
  87944. else {
  87945. count *= pixel_size;
  87946. for (i = 0; i < count; ++i) {
  87947. pixel_data[localOffset + i] = data[offset++];
  87948. }
  87949. localOffset += count;
  87950. }
  87951. }
  87952. }
  87953. // RAW Pixels
  87954. else {
  87955. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87956. }
  87957. // Load to texture
  87958. var x_start, y_start, x_step, y_step, y_end, x_end;
  87959. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87960. default:
  87961. case TGATools._ORIGIN_UL:
  87962. x_start = 0;
  87963. x_step = 1;
  87964. x_end = header.width;
  87965. y_start = 0;
  87966. y_step = 1;
  87967. y_end = header.height;
  87968. break;
  87969. case TGATools._ORIGIN_BL:
  87970. x_start = 0;
  87971. x_step = 1;
  87972. x_end = header.width;
  87973. y_start = header.height - 1;
  87974. y_step = -1;
  87975. y_end = -1;
  87976. break;
  87977. case TGATools._ORIGIN_UR:
  87978. x_start = header.width - 1;
  87979. x_step = -1;
  87980. x_end = -1;
  87981. y_start = 0;
  87982. y_step = 1;
  87983. y_end = header.height;
  87984. break;
  87985. case TGATools._ORIGIN_BR:
  87986. x_start = header.width - 1;
  87987. x_step = -1;
  87988. x_end = -1;
  87989. y_start = header.height - 1;
  87990. y_step = -1;
  87991. y_end = -1;
  87992. break;
  87993. }
  87994. // Load the specify method
  87995. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87996. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87997. var engine = texture.getEngine();
  87998. engine._uploadDataToTextureDirectly(texture, imageData);
  87999. };
  88000. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88001. var image = pixel_data, colormap = palettes;
  88002. var width = header.width, height = header.height;
  88003. var color, i = 0, x, y;
  88004. var imageData = new Uint8Array(width * height * 4);
  88005. for (y = y_start; y !== y_end; y += y_step) {
  88006. for (x = x_start; x !== x_end; x += x_step, i++) {
  88007. color = image[i];
  88008. imageData[(x + width * y) * 4 + 3] = 255;
  88009. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  88010. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  88011. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  88012. }
  88013. }
  88014. return imageData;
  88015. };
  88016. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88017. var image = pixel_data;
  88018. var width = header.width, height = header.height;
  88019. var color, i = 0, x, y;
  88020. var imageData = new Uint8Array(width * height * 4);
  88021. for (y = y_start; y !== y_end; y += y_step) {
  88022. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88023. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  88024. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  88025. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  88026. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  88027. imageData[(x + width * y) * 4 + 0] = r;
  88028. imageData[(x + width * y) * 4 + 1] = g;
  88029. imageData[(x + width * y) * 4 + 2] = b;
  88030. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  88031. }
  88032. }
  88033. return imageData;
  88034. };
  88035. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88036. var image = pixel_data;
  88037. var width = header.width, height = header.height;
  88038. var i = 0, x, y;
  88039. var imageData = new Uint8Array(width * height * 4);
  88040. for (y = y_start; y !== y_end; y += y_step) {
  88041. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  88042. imageData[(x + width * y) * 4 + 3] = 255;
  88043. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88044. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88045. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88046. }
  88047. }
  88048. return imageData;
  88049. };
  88050. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88051. var image = pixel_data;
  88052. var width = header.width, height = header.height;
  88053. var i = 0, x, y;
  88054. var imageData = new Uint8Array(width * height * 4);
  88055. for (y = y_start; y !== y_end; y += y_step) {
  88056. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  88057. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88058. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88059. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88060. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  88061. }
  88062. }
  88063. return imageData;
  88064. };
  88065. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88066. var image = pixel_data;
  88067. var width = header.width, height = header.height;
  88068. var color, i = 0, x, y;
  88069. var imageData = new Uint8Array(width * height * 4);
  88070. for (y = y_start; y !== y_end; y += y_step) {
  88071. for (x = x_start; x !== x_end; x += x_step, i++) {
  88072. color = image[i];
  88073. imageData[(x + width * y) * 4 + 0] = color;
  88074. imageData[(x + width * y) * 4 + 1] = color;
  88075. imageData[(x + width * y) * 4 + 2] = color;
  88076. imageData[(x + width * y) * 4 + 3] = 255;
  88077. }
  88078. }
  88079. return imageData;
  88080. };
  88081. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88082. var image = pixel_data;
  88083. var width = header.width, height = header.height;
  88084. var i = 0, x, y;
  88085. var imageData = new Uint8Array(width * height * 4);
  88086. for (y = y_start; y !== y_end; y += y_step) {
  88087. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88088. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  88089. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  88090. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88091. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  88092. }
  88093. }
  88094. return imageData;
  88095. };
  88096. //private static _TYPE_NO_DATA = 0;
  88097. TGATools._TYPE_INDEXED = 1;
  88098. TGATools._TYPE_RGB = 2;
  88099. TGATools._TYPE_GREY = 3;
  88100. TGATools._TYPE_RLE_INDEXED = 9;
  88101. TGATools._TYPE_RLE_RGB = 10;
  88102. TGATools._TYPE_RLE_GREY = 11;
  88103. TGATools._ORIGIN_MASK = 0x30;
  88104. TGATools._ORIGIN_SHIFT = 0x04;
  88105. TGATools._ORIGIN_BL = 0x00;
  88106. TGATools._ORIGIN_BR = 0x01;
  88107. TGATools._ORIGIN_UL = 0x02;
  88108. TGATools._ORIGIN_UR = 0x03;
  88109. return TGATools;
  88110. }());
  88111. BABYLON.TGATools = TGATools;
  88112. })(BABYLON || (BABYLON = {}));
  88113. //# sourceMappingURL=babylon.tga.js.map
  88114. var BABYLON;
  88115. (function (BABYLON) {
  88116. /**
  88117. * Implementation of the TGA Texture Loader.
  88118. */
  88119. var TGATextureLoader = /** @class */ (function () {
  88120. function TGATextureLoader() {
  88121. /**
  88122. * Defines wether the loader supports cascade loading the different faces.
  88123. */
  88124. this.supportCascades = false;
  88125. }
  88126. /**
  88127. * This returns if the loader support the current file information.
  88128. * @param extension defines the file extension of the file being loaded
  88129. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88130. * @param fallback defines the fallback internal texture if any
  88131. * @param isBase64 defines whether the texture is encoded as a base64
  88132. * @param isBuffer defines whether the texture data are stored as a buffer
  88133. * @returns true if the loader can load the specified file
  88134. */
  88135. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88136. return extension.indexOf(".tga") === 0;
  88137. };
  88138. /**
  88139. * Transform the url before loading if required.
  88140. * @param rootUrl the url of the texture
  88141. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88142. * @returns the transformed texture
  88143. */
  88144. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88145. return rootUrl;
  88146. };
  88147. /**
  88148. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88149. * @param rootUrl the url of the texture
  88150. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88151. * @returns the fallback texture
  88152. */
  88153. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88154. return null;
  88155. };
  88156. /**
  88157. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88158. * @param data contains the texture data
  88159. * @param texture defines the BabylonJS internal texture
  88160. * @param createPolynomials will be true if polynomials have been requested
  88161. * @param onLoad defines the callback to trigger once the texture is ready
  88162. * @param onError defines the callback to trigger in case of error
  88163. */
  88164. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88165. throw ".env not supported in Cube.";
  88166. };
  88167. /**
  88168. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88169. * @param data contains the texture data
  88170. * @param texture defines the BabylonJS internal texture
  88171. * @param callback defines the method to call once ready to upload
  88172. */
  88173. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  88174. var uintData = new Uint8Array(data);
  88175. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  88176. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  88177. BABYLON.TGATools.UploadContent(texture, uintData);
  88178. });
  88179. };
  88180. return TGATextureLoader;
  88181. }());
  88182. // Register the loader.
  88183. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  88184. })(BABYLON || (BABYLON = {}));
  88185. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  88186. var BABYLON;
  88187. (function (BABYLON) {
  88188. /**
  88189. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88190. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88191. */
  88192. var KhronosTextureContainer = /** @class */ (function () {
  88193. /**
  88194. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88195. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88196. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88197. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88198. */
  88199. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88200. this.arrayBuffer = arrayBuffer;
  88201. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88202. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88203. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88204. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88205. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88206. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88207. BABYLON.Tools.Error("texture missing KTX identifier");
  88208. return;
  88209. }
  88210. // load the reset of the header in native 32 bit int
  88211. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88212. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88213. var oppositeEndianess = header[0] === 0x01020304;
  88214. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88215. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88216. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88217. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88218. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88219. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88220. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88221. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88222. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88223. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88224. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88225. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88226. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88227. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88228. if (this.glType !== 0) {
  88229. BABYLON.Tools.Error("only compressed formats currently supported");
  88230. return;
  88231. }
  88232. else {
  88233. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88234. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88235. }
  88236. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88237. BABYLON.Tools.Error("only 2D textures currently supported");
  88238. return;
  88239. }
  88240. if (this.numberOfArrayElements !== 0) {
  88241. BABYLON.Tools.Error("texture arrays not currently supported");
  88242. return;
  88243. }
  88244. if (this.numberOfFaces !== facesExpected) {
  88245. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88246. return;
  88247. }
  88248. // we now have a completely validated file, so could use existence of loadType as success
  88249. // would need to make this more elaborate & adjust checks above to support more than one load type
  88250. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88251. }
  88252. // not as fast hardware based, but will probably never need to use
  88253. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88254. return ((val & 0xFF) << 24)
  88255. | ((val & 0xFF00) << 8)
  88256. | ((val >> 8) & 0xFF00)
  88257. | ((val >> 24) & 0xFF);
  88258. };
  88259. /**
  88260. * Uploads KTX content to a Babylon Texture.
  88261. * It is assumed that the texture has already been created & is currently bound
  88262. * @hidden
  88263. */
  88264. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  88265. switch (this.loadType) {
  88266. case KhronosTextureContainer.COMPRESSED_2D:
  88267. this._upload2DCompressedLevels(texture, loadMipmaps);
  88268. break;
  88269. case KhronosTextureContainer.TEX_2D:
  88270. case KhronosTextureContainer.COMPRESSED_3D:
  88271. case KhronosTextureContainer.TEX_3D:
  88272. }
  88273. };
  88274. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  88275. // initialize width & height for level 1
  88276. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  88277. var width = this.pixelWidth;
  88278. var height = this.pixelHeight;
  88279. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  88280. for (var level = 0; level < mipmapCount; level++) {
  88281. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  88282. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  88283. for (var face = 0; face < this.numberOfFaces; face++) {
  88284. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  88285. var engine = texture.getEngine();
  88286. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  88287. dataOffset += imageSize; // add size of the image for the next face/mipmap
  88288. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  88289. }
  88290. width = Math.max(1.0, width * 0.5);
  88291. height = Math.max(1.0, height * 0.5);
  88292. }
  88293. };
  88294. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  88295. // load types
  88296. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  88297. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  88298. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  88299. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  88300. return KhronosTextureContainer;
  88301. }());
  88302. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  88303. })(BABYLON || (BABYLON = {}));
  88304. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  88305. var BABYLON;
  88306. (function (BABYLON) {
  88307. /**
  88308. * Implementation of the KTX Texture Loader.
  88309. */
  88310. var KTXTextureLoader = /** @class */ (function () {
  88311. function KTXTextureLoader() {
  88312. /**
  88313. * Defines wether the loader supports cascade loading the different faces.
  88314. */
  88315. this.supportCascades = false;
  88316. }
  88317. /**
  88318. * This returns if the loader support the current file information.
  88319. * @param extension defines the file extension of the file being loaded
  88320. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88321. * @param fallback defines the fallback internal texture if any
  88322. * @param isBase64 defines whether the texture is encoded as a base64
  88323. * @param isBuffer defines whether the texture data are stored as a buffer
  88324. * @returns true if the loader can load the specified file
  88325. */
  88326. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88327. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  88328. return true;
  88329. }
  88330. return false;
  88331. };
  88332. /**
  88333. * Transform the url before loading if required.
  88334. * @param rootUrl the url of the texture
  88335. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88336. * @returns the transformed texture
  88337. */
  88338. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88339. var lastDot = rootUrl.lastIndexOf('.');
  88340. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  88341. };
  88342. /**
  88343. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88344. * @param rootUrl the url of the texture
  88345. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88346. * @returns the fallback texture
  88347. */
  88348. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88349. // remove the format appended to the rootUrl in the original createCubeTexture call.
  88350. var exp = new RegExp("" + textureFormatInUse + "$");
  88351. return rootUrl.replace(exp, "");
  88352. };
  88353. /**
  88354. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88355. * @param data contains the texture data
  88356. * @param texture defines the BabylonJS internal texture
  88357. * @param createPolynomials will be true if polynomials have been requested
  88358. * @param onLoad defines the callback to trigger once the texture is ready
  88359. * @param onError defines the callback to trigger in case of error
  88360. */
  88361. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88362. if (Array.isArray(data)) {
  88363. return;
  88364. }
  88365. var engine = texture.getEngine();
  88366. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  88367. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  88368. engine._unpackFlipY(true);
  88369. ktx.uploadLevels(texture, texture.generateMipMaps);
  88370. texture.width = ktx.pixelWidth;
  88371. texture.height = ktx.pixelHeight;
  88372. engine._setCubeMapTextureParams(loadMipmap);
  88373. texture.isReady = true;
  88374. };
  88375. /**
  88376. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88377. * @param data contains the texture data
  88378. * @param texture defines the BabylonJS internal texture
  88379. * @param callback defines the method to call once ready to upload
  88380. */
  88381. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  88382. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  88383. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  88384. ktx.uploadLevels(texture, texture.generateMipMaps);
  88385. });
  88386. };
  88387. return KTXTextureLoader;
  88388. }());
  88389. // Register the loader.
  88390. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  88391. })(BABYLON || (BABYLON = {}));
  88392. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  88393. var BABYLON;
  88394. (function (BABYLON) {
  88395. /**
  88396. * Sets of helpers addressing the serialization and deserialization of environment texture
  88397. * stored in a BabylonJS env file.
  88398. * Those files are usually stored as .env files.
  88399. */
  88400. var EnvironmentTextureTools = /** @class */ (function () {
  88401. function EnvironmentTextureTools() {
  88402. }
  88403. /**
  88404. * Gets the environment info from an env file.
  88405. * @param data The array buffer containing the .env bytes.
  88406. * @returns the environment file info (the json header) if successfully parsed.
  88407. */
  88408. EnvironmentTextureTools.GetEnvInfo = function (data) {
  88409. var dataView = new DataView(data);
  88410. var pos = 0;
  88411. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88412. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  88413. BABYLON.Tools.Error('Not a babylon environment map');
  88414. return null;
  88415. }
  88416. }
  88417. // Read json manifest - collect characters up to null terminator
  88418. var manifestString = '';
  88419. var charCode = 0x00;
  88420. while ((charCode = dataView.getUint8(pos++))) {
  88421. manifestString += String.fromCharCode(charCode);
  88422. }
  88423. var manifest = JSON.parse(manifestString);
  88424. if (manifest.specular) {
  88425. // Extend the header with the position of the payload.
  88426. manifest.specular.specularDataPosition = pos;
  88427. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  88428. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  88429. }
  88430. return manifest;
  88431. };
  88432. /**
  88433. * Creates an environment texture from a loaded cube texture.
  88434. * @param texture defines the cube texture to convert in env file
  88435. * @return a promise containing the environment data if succesfull.
  88436. */
  88437. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  88438. var _this = this;
  88439. var internalTexture = texture.getInternalTexture();
  88440. if (!internalTexture) {
  88441. return Promise.reject("The cube texture is invalid.");
  88442. }
  88443. if (!texture._prefiltered) {
  88444. return Promise.reject("The cube texture is invalid (not prefiltered).");
  88445. }
  88446. var engine = internalTexture.getEngine();
  88447. if (engine && engine.premultipliedAlpha) {
  88448. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  88449. }
  88450. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  88451. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  88452. }
  88453. var canvas = engine.getRenderingCanvas();
  88454. if (!canvas) {
  88455. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  88456. }
  88457. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88458. if (!engine.getCaps().textureFloatRender) {
  88459. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88460. if (!engine.getCaps().textureHalfFloatRender) {
  88461. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  88462. }
  88463. }
  88464. var cubeWidth = internalTexture.width;
  88465. var hostingScene = new BABYLON.Scene(engine);
  88466. var specularTextures = {};
  88467. var promises = [];
  88468. // Read and collect all mipmaps data from the cube.
  88469. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  88470. mipmapsCount = Math.round(mipmapsCount);
  88471. var _loop_1 = function (i) {
  88472. var faceWidth = Math.pow(2, mipmapsCount - i);
  88473. var _loop_2 = function (face) {
  88474. var data = texture.readPixels(face, i);
  88475. // Creates a temp texture with the face data.
  88476. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  88477. // And rgbdEncode them.
  88478. var promise = new Promise(function (resolve, reject) {
  88479. 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);
  88480. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88481. rgbdPostProcess.onApply = function (effect) {
  88482. effect._bindTexture("textureSampler", tempTexture);
  88483. };
  88484. // As the process needs to happen on the main canvas, keep track of the current size
  88485. var currentW = engine.getRenderWidth();
  88486. var currentH = engine.getRenderHeight();
  88487. // Set the desired size for the texture
  88488. engine.setSize(faceWidth, faceWidth);
  88489. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  88490. // Reading datas from WebGL
  88491. BABYLON.Tools.ToBlob(canvas, function (blob) {
  88492. var fileReader = new FileReader();
  88493. fileReader.onload = function (event) {
  88494. var arrayBuffer = event.target.result;
  88495. specularTextures[i * 6 + face] = arrayBuffer;
  88496. resolve();
  88497. };
  88498. fileReader.readAsArrayBuffer(blob);
  88499. });
  88500. // Reapply the previous canvas size
  88501. engine.setSize(currentW, currentH);
  88502. });
  88503. });
  88504. promises.push(promise);
  88505. };
  88506. // All faces of the cube.
  88507. for (var face = 0; face < 6; face++) {
  88508. _loop_2(face);
  88509. }
  88510. };
  88511. for (var i = 0; i <= mipmapsCount; i++) {
  88512. _loop_1(i);
  88513. }
  88514. // Once all the textures haves been collected as RGBD stored in PNGs
  88515. return Promise.all(promises).then(function () {
  88516. // We can delete the hosting scene keeping track of all the creation objects
  88517. hostingScene.dispose();
  88518. // Creates the json header for the env texture
  88519. var info = {
  88520. version: 1,
  88521. width: cubeWidth,
  88522. irradiance: _this._CreateEnvTextureIrradiance(texture),
  88523. specular: {
  88524. mipmaps: [],
  88525. lodGenerationScale: texture.lodGenerationScale
  88526. }
  88527. };
  88528. // Sets the specular image data information
  88529. var position = 0;
  88530. for (var i = 0; i <= mipmapsCount; i++) {
  88531. for (var face = 0; face < 6; face++) {
  88532. var byteLength = specularTextures[i * 6 + face].byteLength;
  88533. info.specular.mipmaps.push({
  88534. length: byteLength,
  88535. position: position
  88536. });
  88537. position += byteLength;
  88538. }
  88539. }
  88540. // Encode the JSON as an array buffer
  88541. var infoString = JSON.stringify(info);
  88542. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  88543. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  88544. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  88545. infoView[i] = infoString.charCodeAt(i);
  88546. }
  88547. // Ends up with a null terminator for easier parsing
  88548. infoView[infoString.length] = 0x00;
  88549. // Computes the final required size and creates the storage
  88550. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  88551. var finalBuffer = new ArrayBuffer(totalSize);
  88552. var finalBufferView = new Uint8Array(finalBuffer);
  88553. var dataView = new DataView(finalBuffer);
  88554. // Copy the magic bytes identifying the file in
  88555. var pos = 0;
  88556. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88557. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  88558. }
  88559. // Add the json info
  88560. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  88561. pos += infoBuffer.byteLength;
  88562. // Finally inserts the texture data
  88563. for (var i = 0; i <= mipmapsCount; i++) {
  88564. for (var face = 0; face < 6; face++) {
  88565. var dataBuffer = specularTextures[i * 6 + face];
  88566. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  88567. pos += dataBuffer.byteLength;
  88568. }
  88569. }
  88570. // Voila
  88571. return finalBuffer;
  88572. });
  88573. };
  88574. /**
  88575. * Creates a JSON representation of the spherical data.
  88576. * @param texture defines the texture containing the polynomials
  88577. * @return the JSON representation of the spherical info
  88578. */
  88579. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  88580. var polynmials = texture.sphericalPolynomial;
  88581. if (polynmials == null) {
  88582. return null;
  88583. }
  88584. return {
  88585. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  88586. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  88587. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  88588. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  88589. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  88590. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  88591. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  88592. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  88593. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  88594. };
  88595. };
  88596. /**
  88597. * Uploads the texture info contained in the env file to the GPU.
  88598. * @param texture defines the internal texture to upload to
  88599. * @param arrayBuffer defines the buffer cotaining the data to load
  88600. * @param info defines the texture info retrieved through the GetEnvInfo method
  88601. * @returns a promise
  88602. */
  88603. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  88604. if (info.version !== 1) {
  88605. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  88606. }
  88607. var specularInfo = info.specular;
  88608. if (!specularInfo) {
  88609. // Nothing else parsed so far
  88610. return Promise.resolve();
  88611. }
  88612. // Double checks the enclosed info
  88613. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  88614. mipmapsCount = Math.round(mipmapsCount) + 1;
  88615. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  88616. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  88617. }
  88618. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  88619. var imageData = new Array(mipmapsCount);
  88620. for (var i = 0; i < mipmapsCount; i++) {
  88621. imageData[i] = new Array(6);
  88622. for (var face = 0; face < 6; face++) {
  88623. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  88624. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  88625. }
  88626. }
  88627. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  88628. };
  88629. /**
  88630. * Uploads the levels of image data to the GPU.
  88631. * @param texture defines the internal texture to upload to
  88632. * @param imageData defines the array buffer views of image data [mipmap][face]
  88633. * @returns a promise
  88634. */
  88635. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  88636. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  88637. throw new Error("Texture size must be a power of two");
  88638. }
  88639. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  88640. // Gets everything ready.
  88641. var engine = texture.getEngine();
  88642. var expandTexture = false;
  88643. var generateNonLODTextures = false;
  88644. var rgbdPostProcess = null;
  88645. var cubeRtt = null;
  88646. var lodTextures = null;
  88647. var caps = engine.getCaps();
  88648. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88649. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88650. texture.generateMipMaps = true;
  88651. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  88652. // Add extra process if texture lod is not supported
  88653. if (!caps.textureLOD) {
  88654. expandTexture = false;
  88655. generateNonLODTextures = true;
  88656. lodTextures = {};
  88657. }
  88658. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  88659. else if (engine.webGLVersion < 2) {
  88660. expandTexture = false;
  88661. }
  88662. // If half float available we can uncompress the texture
  88663. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  88664. expandTexture = true;
  88665. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88666. }
  88667. // If full float available we can uncompress the texture
  88668. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  88669. expandTexture = true;
  88670. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88671. }
  88672. // Expand the texture if possible
  88673. if (expandTexture) {
  88674. // Simply run through the decode PP
  88675. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  88676. texture._isRGBD = false;
  88677. texture.invertY = false;
  88678. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  88679. generateDepthBuffer: false,
  88680. generateMipMaps: true,
  88681. generateStencilBuffer: false,
  88682. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  88683. type: texture.type,
  88684. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  88685. });
  88686. }
  88687. else {
  88688. texture._isRGBD = true;
  88689. texture.invertY = true;
  88690. // In case of missing support, applies the same patch than DDS files.
  88691. if (generateNonLODTextures) {
  88692. var mipSlices = 3;
  88693. var scale = texture._lodGenerationScale;
  88694. var offset = texture._lodGenerationOffset;
  88695. for (var i = 0; i < mipSlices; i++) {
  88696. //compute LOD from even spacing in smoothness (matching shader calculation)
  88697. var smoothness = i / (mipSlices - 1);
  88698. var roughness = 1 - smoothness;
  88699. var minLODIndex = offset; // roughness = 0
  88700. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  88701. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  88702. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  88703. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  88704. glTextureFromLod.isCube = true;
  88705. glTextureFromLod.invertY = true;
  88706. glTextureFromLod.generateMipMaps = false;
  88707. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  88708. // Wrap in a base texture for easy binding.
  88709. var lodTexture = new BABYLON.BaseTexture(null);
  88710. lodTexture.isCube = true;
  88711. lodTexture._texture = glTextureFromLod;
  88712. lodTextures[mipmapIndex] = lodTexture;
  88713. switch (i) {
  88714. case 0:
  88715. texture._lodTextureLow = lodTexture;
  88716. break;
  88717. case 1:
  88718. texture._lodTextureMid = lodTexture;
  88719. break;
  88720. case 2:
  88721. texture._lodTextureHigh = lodTexture;
  88722. break;
  88723. }
  88724. }
  88725. }
  88726. }
  88727. var promises = [];
  88728. var _loop_3 = function (i) {
  88729. var _loop_4 = function (face) {
  88730. // Constructs an image element from image data
  88731. var bytes = imageData[i][face];
  88732. var blob = new Blob([bytes], { type: 'image/png' });
  88733. var url = URL.createObjectURL(blob);
  88734. var image = new Image();
  88735. image.src = url;
  88736. // Enqueue promise to upload to the texture.
  88737. var promise = new Promise(function (resolve, reject) {
  88738. image.onload = function () {
  88739. if (expandTexture) {
  88740. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  88741. reject(message);
  88742. }, image);
  88743. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88744. // Uncompress the data to a RTT
  88745. rgbdPostProcess.onApply = function (effect) {
  88746. effect._bindTexture("textureSampler", tempTexture_1);
  88747. effect.setFloat2("scale", 1, 1);
  88748. };
  88749. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  88750. // Cleanup
  88751. engine.restoreDefaultFramebuffer();
  88752. tempTexture_1.dispose();
  88753. window.URL.revokeObjectURL(url);
  88754. resolve();
  88755. });
  88756. }
  88757. else {
  88758. engine._uploadImageToTexture(texture, image, face, i);
  88759. // Upload the face to the non lod texture support
  88760. if (generateNonLODTextures) {
  88761. var lodTexture = lodTextures[i];
  88762. if (lodTexture) {
  88763. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  88764. }
  88765. }
  88766. resolve();
  88767. }
  88768. };
  88769. image.onerror = function (error) {
  88770. reject(error);
  88771. };
  88772. });
  88773. promises.push(promise);
  88774. };
  88775. // All faces
  88776. for (var face = 0; face < 6; face++) {
  88777. _loop_4(face);
  88778. }
  88779. };
  88780. // All mipmaps up to provided number of images
  88781. for (var i = 0; i < imageData.length; i++) {
  88782. _loop_3(i);
  88783. }
  88784. // Fill remaining mipmaps with black textures.
  88785. if (imageData.length < mipmapsCount) {
  88786. var data = void 0;
  88787. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  88788. var dataLength = size * size * 4;
  88789. switch (texture.type) {
  88790. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  88791. data = new Uint8Array(dataLength);
  88792. break;
  88793. }
  88794. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  88795. data = new Uint16Array(dataLength);
  88796. break;
  88797. }
  88798. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  88799. data = new Float32Array(dataLength);
  88800. break;
  88801. }
  88802. }
  88803. for (var i = imageData.length; i < mipmapsCount; i++) {
  88804. for (var face = 0; face < 6; face++) {
  88805. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  88806. }
  88807. }
  88808. }
  88809. // Once all done, finishes the cleanup and return
  88810. return Promise.all(promises).then(function () {
  88811. // Release temp RTT.
  88812. if (cubeRtt) {
  88813. engine._releaseFramebufferObjects(cubeRtt);
  88814. cubeRtt._swapAndDie(texture);
  88815. }
  88816. // Release temp Post Process.
  88817. if (rgbdPostProcess) {
  88818. rgbdPostProcess.dispose();
  88819. }
  88820. // Flag internal texture as ready in case they are in use.
  88821. if (generateNonLODTextures) {
  88822. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  88823. texture._lodTextureHigh._texture.isReady = true;
  88824. }
  88825. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  88826. texture._lodTextureMid._texture.isReady = true;
  88827. }
  88828. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  88829. texture._lodTextureLow._texture.isReady = true;
  88830. }
  88831. }
  88832. });
  88833. };
  88834. /**
  88835. * Uploads spherical polynomials information to the texture.
  88836. * @param texture defines the texture we are trying to upload the information to
  88837. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  88838. */
  88839. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  88840. if (info.version !== 1) {
  88841. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  88842. }
  88843. var irradianceInfo = info.irradiance;
  88844. if (!irradianceInfo) {
  88845. return;
  88846. }
  88847. var sp = new BABYLON.SphericalPolynomial();
  88848. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  88849. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  88850. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  88851. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  88852. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  88853. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  88854. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  88855. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  88856. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  88857. texture._sphericalPolynomial = sp;
  88858. };
  88859. /**
  88860. * Magic number identifying the env file.
  88861. */
  88862. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  88863. return EnvironmentTextureTools;
  88864. }());
  88865. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  88866. })(BABYLON || (BABYLON = {}));
  88867. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  88868. var BABYLON;
  88869. (function (BABYLON) {
  88870. /**
  88871. * Implementation of the ENV Texture Loader.
  88872. */
  88873. var ENVTextureLoader = /** @class */ (function () {
  88874. function ENVTextureLoader() {
  88875. /**
  88876. * Defines wether the loader supports cascade loading the different faces.
  88877. */
  88878. this.supportCascades = false;
  88879. }
  88880. /**
  88881. * This returns if the loader support the current file information.
  88882. * @param extension defines the file extension of the file being loaded
  88883. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88884. * @param fallback defines the fallback internal texture if any
  88885. * @param isBase64 defines whether the texture is encoded as a base64
  88886. * @param isBuffer defines whether the texture data are stored as a buffer
  88887. * @returns true if the loader can load the specified file
  88888. */
  88889. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88890. return extension.indexOf(".env") === 0;
  88891. };
  88892. /**
  88893. * Transform the url before loading if required.
  88894. * @param rootUrl the url of the texture
  88895. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88896. * @returns the transformed texture
  88897. */
  88898. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88899. return rootUrl;
  88900. };
  88901. /**
  88902. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88903. * @param rootUrl the url of the texture
  88904. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88905. * @returns the fallback texture
  88906. */
  88907. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88908. return null;
  88909. };
  88910. /**
  88911. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88912. * @param data contains the texture data
  88913. * @param texture defines the BabylonJS internal texture
  88914. * @param createPolynomials will be true if polynomials have been requested
  88915. * @param onLoad defines the callback to trigger once the texture is ready
  88916. * @param onError defines the callback to trigger in case of error
  88917. */
  88918. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88919. if (Array.isArray(data)) {
  88920. return;
  88921. }
  88922. data = data;
  88923. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  88924. if (info) {
  88925. texture.width = info.width;
  88926. texture.height = info.width;
  88927. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  88928. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  88929. texture.isReady = true;
  88930. if (onLoad) {
  88931. onLoad();
  88932. }
  88933. });
  88934. }
  88935. else if (onError) {
  88936. onError("Can not parse the environment file", null);
  88937. }
  88938. };
  88939. /**
  88940. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88941. * @param data contains the texture data
  88942. * @param texture defines the BabylonJS internal texture
  88943. * @param callback defines the method to call once ready to upload
  88944. */
  88945. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  88946. throw ".env not supported in 2d.";
  88947. };
  88948. return ENVTextureLoader;
  88949. }());
  88950. // Register the loader.
  88951. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  88952. })(BABYLON || (BABYLON = {}));
  88953. //# sourceMappingURL=babylon.envTextureLoader.js.map
  88954. var BABYLON;
  88955. (function (BABYLON) {
  88956. /**
  88957. * Renders a layer on top of an existing scene
  88958. */
  88959. var UtilityLayerRenderer = /** @class */ (function () {
  88960. /**
  88961. * Instantiates a UtilityLayerRenderer
  88962. * @param originalScene the original scene that will be rendered on top of
  88963. */
  88964. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88965. var _this = this;
  88966. this.originalScene = originalScene;
  88967. this._pointerCaptures = {};
  88968. this._lastPointerEvents = {};
  88969. /**
  88970. * If the utility layer should automatically be rendered on top of existing scene
  88971. */
  88972. this.shouldRender = true;
  88973. /**
  88974. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88975. */
  88976. this.onlyCheckPointerDownEvents = true;
  88977. /**
  88978. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88979. */
  88980. this.processAllEvents = false;
  88981. /**
  88982. * Observable raised when the pointer move from the utility layer scene to the main scene
  88983. */
  88984. this.onPointerOutObservable = new BABYLON.Observable();
  88985. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88986. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88987. this.utilityLayerScene._allowPostProcessClear = false;
  88988. originalScene.getEngine().scenes.pop();
  88989. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88990. this.utilityLayerScene.detachControl();
  88991. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88992. if (!_this.processAllEvents) {
  88993. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88994. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88995. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88996. return;
  88997. }
  88998. }
  88999. var pointerEvent = (prePointerInfo.event);
  89000. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  89001. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89002. return;
  89003. }
  89004. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  89005. if (!prePointerInfo.ray && utilityScenePick) {
  89006. prePointerInfo.ray = utilityScenePick.ray;
  89007. }
  89008. // always fire the prepointer oversvable
  89009. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  89010. // allow every non pointer down event to flow to the utility layer
  89011. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  89012. if (!prePointerInfo.skipOnPointerObservable) {
  89013. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89014. }
  89015. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  89016. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89017. }
  89018. return;
  89019. }
  89020. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  89021. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  89022. if (utilityScenePick && utilityScenePick.hit) {
  89023. if (!prePointerInfo.skipOnPointerObservable) {
  89024. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89025. }
  89026. prePointerInfo.skipOnPointerObservable = true;
  89027. }
  89028. }
  89029. else {
  89030. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  89031. var pointerEvent_1 = (prePointerInfo.event);
  89032. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  89033. if (originalScenePick && utilityScenePick) {
  89034. // No pick in utility scene
  89035. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  89036. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89037. // We touched an utility mesh present in the main scene
  89038. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89039. prePointerInfo.skipOnPointerObservable = true;
  89040. }
  89041. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89042. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  89043. }
  89044. }
  89045. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  89046. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  89047. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  89048. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  89049. }
  89050. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  89051. // We have a pick in both scenes but main is closer than utility
  89052. // We touched an utility mesh present in the main scene
  89053. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89054. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89055. prePointerInfo.skipOnPointerObservable = true;
  89056. }
  89057. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  89058. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  89059. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  89060. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  89061. }
  89062. }
  89063. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  89064. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  89065. }
  89066. }
  89067. }
  89068. });
  89069. // Render directly on top of existing scene without clearing
  89070. this.utilityLayerScene.autoClear = false;
  89071. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  89072. if (_this.shouldRender) {
  89073. _this.render();
  89074. }
  89075. });
  89076. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  89077. _this.dispose();
  89078. });
  89079. this._updateCamera();
  89080. }
  89081. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  89082. /**
  89083. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  89084. */
  89085. get: function () {
  89086. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  89087. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89088. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89089. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89090. });
  89091. }
  89092. return UtilityLayerRenderer._DefaultUtilityLayer;
  89093. },
  89094. enumerable: true,
  89095. configurable: true
  89096. });
  89097. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  89098. /**
  89099. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  89100. */
  89101. get: function () {
  89102. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  89103. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89104. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  89105. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89106. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89107. });
  89108. }
  89109. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  89110. },
  89111. enumerable: true,
  89112. configurable: true
  89113. });
  89114. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  89115. if (!prePointerInfo.skipOnPointerObservable) {
  89116. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  89117. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  89118. }
  89119. };
  89120. /**
  89121. * Renders the utility layers scene on top of the original scene
  89122. */
  89123. UtilityLayerRenderer.prototype.render = function () {
  89124. this._updateCamera();
  89125. if (this.utilityLayerScene.activeCamera) {
  89126. // Set the camera's scene to utility layers scene
  89127. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  89128. var camera = this.utilityLayerScene.activeCamera;
  89129. camera._scene = this.utilityLayerScene;
  89130. if (camera.leftCamera) {
  89131. camera.leftCamera._scene = this.utilityLayerScene;
  89132. }
  89133. if (camera.rightCamera) {
  89134. camera.rightCamera._scene = this.utilityLayerScene;
  89135. }
  89136. this.utilityLayerScene.render(false);
  89137. // Reset camera's scene back to original
  89138. camera._scene = oldScene;
  89139. if (camera.leftCamera) {
  89140. camera.leftCamera._scene = oldScene;
  89141. }
  89142. if (camera.rightCamera) {
  89143. camera.rightCamera._scene = oldScene;
  89144. }
  89145. }
  89146. };
  89147. /**
  89148. * Disposes of the renderer
  89149. */
  89150. UtilityLayerRenderer.prototype.dispose = function () {
  89151. this.onPointerOutObservable.clear();
  89152. if (this._afterRenderObserver) {
  89153. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  89154. }
  89155. if (this._sceneDisposeObserver) {
  89156. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89157. }
  89158. if (this._originalPointerObserver) {
  89159. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  89160. }
  89161. this.utilityLayerScene.dispose();
  89162. };
  89163. UtilityLayerRenderer.prototype._updateCamera = function () {
  89164. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  89165. };
  89166. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89167. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89168. return UtilityLayerRenderer;
  89169. }());
  89170. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  89171. })(BABYLON || (BABYLON = {}));
  89172. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  89173. //# sourceMappingURL=babylon.behavior.js.map
  89174. var BABYLON;
  89175. (function (BABYLON) {
  89176. /**
  89177. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  89178. */
  89179. var PointerDragBehavior = /** @class */ (function () {
  89180. /**
  89181. * Creates a pointer drag behavior that can be attached to a mesh
  89182. * @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)
  89183. */
  89184. function PointerDragBehavior(options) {
  89185. /**
  89186. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  89187. */
  89188. this.maxDragAngle = 0;
  89189. /**
  89190. * @hidden
  89191. */
  89192. this._useAlternatePickedPointAboveMaxDragAngle = false;
  89193. /**
  89194. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89195. */
  89196. this.currentDraggingPointerID = -1;
  89197. /**
  89198. * If the behavior is currently in a dragging state
  89199. */
  89200. this.dragging = false;
  89201. /**
  89202. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89203. */
  89204. this.dragDeltaRatio = 0.2;
  89205. /**
  89206. * If the drag plane orientation should be updated during the dragging (Default: true)
  89207. */
  89208. this.updateDragPlane = true;
  89209. // Debug mode will display drag planes to help visualize behavior
  89210. this._debugMode = false;
  89211. this._moving = false;
  89212. /**
  89213. * Fires each time the attached mesh is dragged with the pointer
  89214. * * delta between last drag position and current drag position in world space
  89215. * * dragDistance along the drag axis
  89216. * * dragPlaneNormal normal of the current drag plane used during the drag
  89217. * * dragPlanePoint in world space where the drag intersects the drag plane
  89218. */
  89219. this.onDragObservable = new BABYLON.Observable();
  89220. /**
  89221. * Fires each time a drag begins (eg. mouse down on mesh)
  89222. */
  89223. this.onDragStartObservable = new BABYLON.Observable();
  89224. /**
  89225. * Fires each time a drag ends (eg. mouse release after drag)
  89226. */
  89227. this.onDragEndObservable = new BABYLON.Observable();
  89228. /**
  89229. * If the attached mesh should be moved when dragged
  89230. */
  89231. this.moveAttached = true;
  89232. /**
  89233. * If the drag behavior will react to drag events (Default: true)
  89234. */
  89235. this.enabled = true;
  89236. /**
  89237. * If camera controls should be detached during the drag
  89238. */
  89239. this.detachCameraControls = true;
  89240. /**
  89241. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  89242. */
  89243. this.useObjectOrienationForDragging = true;
  89244. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89245. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  89246. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  89247. // Variables to avoid instantiation in the below method
  89248. this._pointA = new BABYLON.Vector3(0, 0, 0);
  89249. this._pointB = new BABYLON.Vector3(0, 0, 0);
  89250. this._pointC = new BABYLON.Vector3(0, 0, 0);
  89251. this._lineA = new BABYLON.Vector3(0, 0, 0);
  89252. this._lineB = new BABYLON.Vector3(0, 0, 0);
  89253. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  89254. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  89255. this._options = options ? options : {};
  89256. var optionCount = 0;
  89257. if (this._options.dragAxis) {
  89258. optionCount++;
  89259. }
  89260. if (this._options.dragPlaneNormal) {
  89261. optionCount++;
  89262. }
  89263. if (optionCount > 1) {
  89264. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  89265. }
  89266. }
  89267. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  89268. /**
  89269. * The name of the behavior
  89270. */
  89271. get: function () {
  89272. return "PointerDrag";
  89273. },
  89274. enumerable: true,
  89275. configurable: true
  89276. });
  89277. /**
  89278. * Initializes the behavior
  89279. */
  89280. PointerDragBehavior.prototype.init = function () { };
  89281. /**
  89282. * Attaches the drag behavior the passed in mesh
  89283. * @param ownerNode The mesh that will be dragged around once attached
  89284. */
  89285. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89286. var _this = this;
  89287. this._scene = ownerNode.getScene();
  89288. this._attachedNode = ownerNode;
  89289. // Initialize drag plane to not interfere with existing scene
  89290. if (!PointerDragBehavior._planeScene) {
  89291. if (this._debugMode) {
  89292. PointerDragBehavior._planeScene = this._scene;
  89293. }
  89294. else {
  89295. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89296. PointerDragBehavior._planeScene.detachControl();
  89297. this._scene.getEngine().scenes.pop();
  89298. this._scene.onDisposeObservable.addOnce(function () {
  89299. PointerDragBehavior._planeScene.dispose();
  89300. PointerDragBehavior._planeScene = null;
  89301. });
  89302. }
  89303. }
  89304. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89305. // State of the drag
  89306. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89307. var delta = new BABYLON.Vector3(0, 0, 0);
  89308. var dragLength = 0;
  89309. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89310. var pickPredicate = function (m) {
  89311. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89312. };
  89313. var attachedElement = null;
  89314. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89315. if (!_this.enabled) {
  89316. return;
  89317. }
  89318. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89319. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89320. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89321. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89322. if (pickedPoint) {
  89323. _this.dragging = true;
  89324. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89325. _this.lastDragPosition.copyFrom(pickedPoint);
  89326. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89327. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89328. // Detatch camera controls
  89329. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89330. if (_this._scene.activeCamera.inputs.attachedElement) {
  89331. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89332. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89333. }
  89334. else {
  89335. attachedElement = null;
  89336. }
  89337. }
  89338. }
  89339. }
  89340. }
  89341. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89342. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89343. _this.releaseDrag();
  89344. // Reattach camera controls
  89345. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89346. _this._scene.activeCamera.attachControl(attachedElement, true);
  89347. }
  89348. }
  89349. }
  89350. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89351. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89352. _this._moving = true;
  89353. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89354. if (pickedPoint) {
  89355. if (_this.updateDragPlane) {
  89356. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89357. }
  89358. // depending on the drag mode option drag accordingly
  89359. if (_this._options.dragAxis) {
  89360. // Convert local drag axis to world
  89361. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89362. // Project delta drag from the drag plane onto the drag axis
  89363. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89364. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89365. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89366. }
  89367. else {
  89368. dragLength = delta.length();
  89369. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89370. }
  89371. targetPosition.addInPlace(delta);
  89372. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89373. _this.lastDragPosition.copyFrom(pickedPoint);
  89374. }
  89375. }
  89376. }
  89377. });
  89378. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89379. if (_this._moving && _this.moveAttached) {
  89380. // Slowly move mesh to avoid jitter
  89381. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89382. _this._tmpVector.scaleInPlace(0.2);
  89383. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89384. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89385. }
  89386. });
  89387. };
  89388. PointerDragBehavior.prototype.releaseDrag = function () {
  89389. this.dragging = false;
  89390. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89391. this.currentDraggingPointerID = -1;
  89392. this._moving = false;
  89393. };
  89394. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89395. var _this = this;
  89396. if (!ray) {
  89397. return null;
  89398. }
  89399. // Calculate angle between plane normal and ray
  89400. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89401. // Correct if ray is casted from oposite side
  89402. if (angle > Math.PI / 2) {
  89403. angle = Math.PI - angle;
  89404. }
  89405. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89406. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89407. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89408. // Invert ray direction along the towards object axis
  89409. this._tmpVector.copyFrom(ray.direction);
  89410. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89411. this._alternatePickedPoint.normalize();
  89412. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89413. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89414. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89415. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89416. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89417. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89418. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89419. return this._alternatePickedPoint;
  89420. }
  89421. else {
  89422. return null;
  89423. }
  89424. }
  89425. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89426. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89427. return pickResult.pickedPoint;
  89428. }
  89429. else {
  89430. return null;
  89431. }
  89432. };
  89433. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89434. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89435. this._pointA.copyFrom(dragPlanePosition);
  89436. if (this._options.dragAxis) {
  89437. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  89438. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89439. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89440. ray.origin.subtractToRef(this._pointA, this._pointC);
  89441. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89442. // Get perpendicular line from direction to camera and drag axis
  89443. this._pointB.subtractToRef(this._pointA, this._lineA);
  89444. this._pointC.subtractToRef(this._pointA, this._lineB);
  89445. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89446. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89447. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89448. this._lookAt.normalize();
  89449. this._dragPlane.position.copyFrom(this._pointA);
  89450. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89451. this._dragPlane.lookAt(this._lookAt);
  89452. }
  89453. else if (this._options.dragPlaneNormal) {
  89454. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  89455. this._dragPlane.position.copyFrom(this._pointA);
  89456. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89457. this._dragPlane.lookAt(this._lookAt);
  89458. }
  89459. else {
  89460. this._dragPlane.position.copyFrom(this._pointA);
  89461. this._dragPlane.lookAt(ray.origin);
  89462. }
  89463. this._dragPlane.computeWorldMatrix(true);
  89464. };
  89465. /**
  89466. * Detaches the behavior from the mesh
  89467. */
  89468. PointerDragBehavior.prototype.detach = function () {
  89469. if (this._pointerObserver) {
  89470. this._scene.onPointerObservable.remove(this._pointerObserver);
  89471. }
  89472. if (this._beforeRenderObserver) {
  89473. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89474. }
  89475. };
  89476. return PointerDragBehavior;
  89477. }());
  89478. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89479. })(BABYLON || (BABYLON = {}));
  89480. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89481. var BABYLON;
  89482. (function (BABYLON) {
  89483. /**
  89484. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89485. */
  89486. var MultiPointerScaleBehavior = /** @class */ (function () {
  89487. function MultiPointerScaleBehavior() {
  89488. this._startDistance = 0;
  89489. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89490. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89491. this._sceneRenderObserver = null;
  89492. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89493. this._dragBehaviorA.moveAttached = false;
  89494. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89495. this._dragBehaviorB.moveAttached = false;
  89496. }
  89497. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89498. /**
  89499. * The name of the behavior
  89500. */
  89501. get: function () {
  89502. return "MultiPointerScale";
  89503. },
  89504. enumerable: true,
  89505. configurable: true
  89506. });
  89507. /**
  89508. * Initializes the behavior
  89509. */
  89510. MultiPointerScaleBehavior.prototype.init = function () { };
  89511. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89512. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89513. };
  89514. /**
  89515. * Attaches the scale behavior the passed in mesh
  89516. * @param ownerNode The mesh that will be scaled around once attached
  89517. */
  89518. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89519. var _this = this;
  89520. this._ownerNode = ownerNode;
  89521. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89522. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89523. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89524. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89525. _this._dragBehaviorA.releaseDrag();
  89526. }
  89527. else {
  89528. _this._initialScale.copyFrom(ownerNode.scaling);
  89529. _this._startDistance = _this._getCurrentDistance();
  89530. }
  89531. }
  89532. });
  89533. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89534. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89535. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89536. _this._dragBehaviorB.releaseDrag();
  89537. }
  89538. else {
  89539. _this._initialScale.copyFrom(ownerNode.scaling);
  89540. _this._startDistance = _this._getCurrentDistance();
  89541. }
  89542. }
  89543. });
  89544. // Once both drag behaviors are active scale based on the distance between the two pointers
  89545. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89546. behavior.onDragObservable.add(function () {
  89547. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89548. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89549. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89550. }
  89551. });
  89552. });
  89553. ownerNode.addBehavior(this._dragBehaviorA);
  89554. ownerNode.addBehavior(this._dragBehaviorB);
  89555. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89556. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89557. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89558. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89559. if (change.length() > 0.01) {
  89560. ownerNode.scaling.addInPlace(change);
  89561. }
  89562. }
  89563. });
  89564. };
  89565. /**
  89566. * Detaches the behavior from the mesh
  89567. */
  89568. MultiPointerScaleBehavior.prototype.detach = function () {
  89569. var _this = this;
  89570. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89571. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89572. behavior.onDragStartObservable.clear();
  89573. behavior.onDragObservable.clear();
  89574. _this._ownerNode.removeBehavior(behavior);
  89575. });
  89576. };
  89577. return MultiPointerScaleBehavior;
  89578. }());
  89579. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89580. })(BABYLON || (BABYLON = {}));
  89581. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89582. var BABYLON;
  89583. (function (BABYLON) {
  89584. /**
  89585. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  89586. */
  89587. var SixDofDragBehavior = /** @class */ (function () {
  89588. function SixDofDragBehavior() {
  89589. this._sceneRenderObserver = null;
  89590. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89591. this._moving = false;
  89592. this._startingOrientation = new BABYLON.Quaternion();
  89593. /**
  89594. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  89595. */
  89596. this.zDragFactor = 3;
  89597. /**
  89598. * If the behavior is currently in a dragging state
  89599. */
  89600. this.dragging = false;
  89601. /**
  89602. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89603. */
  89604. this.dragDeltaRatio = 0.2;
  89605. /**
  89606. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89607. */
  89608. this.currentDraggingPointerID = -1;
  89609. /**
  89610. * If camera controls should be detached during the drag
  89611. */
  89612. this.detachCameraControls = true;
  89613. }
  89614. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89615. /**
  89616. * The name of the behavior
  89617. */
  89618. get: function () {
  89619. return "SixDofDrag";
  89620. },
  89621. enumerable: true,
  89622. configurable: true
  89623. });
  89624. /**
  89625. * Initializes the behavior
  89626. */
  89627. SixDofDragBehavior.prototype.init = function () { };
  89628. /**
  89629. * Attaches the scale behavior the passed in mesh
  89630. * @param ownerNode The mesh that will be scaled around once attached
  89631. */
  89632. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89633. var _this = this;
  89634. this._ownerNode = ownerNode;
  89635. this._scene = this._ownerNode.getScene();
  89636. if (!SixDofDragBehavior._virtualScene) {
  89637. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89638. this._scene.getEngine().scenes.pop();
  89639. }
  89640. var pickedMesh = null;
  89641. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89642. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89643. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89644. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89645. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89646. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89647. var pickPredicate = function (m) {
  89648. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89649. };
  89650. var attachedElement = null;
  89651. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89652. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89653. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89654. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89655. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89656. }
  89657. pickedMesh = _this._ownerNode;
  89658. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89659. // Set position and orientation of the controller
  89660. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89661. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89662. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89663. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89664. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89665. if (!pickedMesh.rotationQuaternion) {
  89666. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89667. }
  89668. var oldParent = pickedMesh.parent;
  89669. pickedMesh.setParent(null);
  89670. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89671. pickedMesh.setParent(oldParent);
  89672. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89673. // Update state
  89674. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89675. _this.dragging = true;
  89676. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89677. // Detatch camera controls
  89678. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89679. if (_this._scene.activeCamera.inputs.attachedElement) {
  89680. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89681. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89682. }
  89683. else {
  89684. attachedElement = null;
  89685. }
  89686. }
  89687. }
  89688. }
  89689. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89690. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89691. _this.dragging = false;
  89692. _this._moving = false;
  89693. _this.currentDraggingPointerID = -1;
  89694. pickedMesh = null;
  89695. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89696. // Reattach camera controls
  89697. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89698. _this._scene.activeCamera.attachControl(attachedElement, true);
  89699. }
  89700. }
  89701. }
  89702. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89703. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89704. var zDragFactor = _this.zDragFactor;
  89705. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89706. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89707. zDragFactor = 0;
  89708. }
  89709. // Calculate controller drag distance in controller space
  89710. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89711. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89712. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  89713. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89714. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89715. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  89716. if (_this._virtualDragMesh.position.z < 0) {
  89717. _this._virtualDragMesh.position.z = 0;
  89718. }
  89719. // Update the controller position
  89720. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89721. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89722. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89723. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89724. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89725. if (pickedMesh.parent) {
  89726. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89727. }
  89728. if (!_this._moving) {
  89729. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89730. }
  89731. _this._moving = true;
  89732. }
  89733. }
  89734. });
  89735. var tmpQuaternion = new BABYLON.Quaternion();
  89736. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89737. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89738. if (_this.dragging && _this._moving && pickedMesh) {
  89739. // Slowly move mesh to avoid jitter
  89740. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89741. // Get change in rotation
  89742. tmpQuaternion.copyFrom(_this._startingOrientation);
  89743. tmpQuaternion.x = -tmpQuaternion.x;
  89744. tmpQuaternion.y = -tmpQuaternion.y;
  89745. tmpQuaternion.z = -tmpQuaternion.z;
  89746. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89747. // Convert change in rotation to only y axis rotation
  89748. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89749. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89750. // Slowly move mesh to avoid jitter
  89751. var oldParent = pickedMesh.parent;
  89752. pickedMesh.setParent(null);
  89753. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89754. pickedMesh.setParent(oldParent);
  89755. }
  89756. });
  89757. };
  89758. /**
  89759. * Detaches the behavior from the mesh
  89760. */
  89761. SixDofDragBehavior.prototype.detach = function () {
  89762. if (this._scene) {
  89763. this._scene.onPointerObservable.remove(this._pointerObserver);
  89764. }
  89765. if (this._ownerNode) {
  89766. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89767. }
  89768. if (this._virtualOriginMesh) {
  89769. this._virtualOriginMesh.dispose();
  89770. }
  89771. if (this._virtualDragMesh) {
  89772. this._virtualDragMesh.dispose();
  89773. }
  89774. };
  89775. return SixDofDragBehavior;
  89776. }());
  89777. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89778. })(BABYLON || (BABYLON = {}));
  89779. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89780. var BABYLON;
  89781. (function (BABYLON) {
  89782. /**
  89783. * @hidden
  89784. */
  89785. var FaceDirectionInfo = /** @class */ (function () {
  89786. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  89787. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  89788. if (diff === void 0) { diff = 0; }
  89789. if (ignore === void 0) { ignore = false; }
  89790. this.direction = direction;
  89791. this.rotatedDirection = rotatedDirection;
  89792. this.diff = diff;
  89793. this.ignore = ignore;
  89794. }
  89795. return FaceDirectionInfo;
  89796. }());
  89797. /**
  89798. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  89799. */
  89800. var AttachToBoxBehavior = /** @class */ (function () {
  89801. /**
  89802. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  89803. * @param ui The transform node that should be attched to the mesh
  89804. */
  89805. function AttachToBoxBehavior(ui) {
  89806. this.ui = ui;
  89807. /**
  89808. * The name of the behavior
  89809. */
  89810. this.name = "AttachToBoxBehavior";
  89811. /**
  89812. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  89813. */
  89814. this.distanceAwayFromFace = 0.15;
  89815. /**
  89816. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  89817. */
  89818. this.distanceAwayFromBottomOfFace = 0.15;
  89819. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  89820. this._tmpMatrix = new BABYLON.Matrix();
  89821. this._tmpVector = new BABYLON.Vector3();
  89822. this._zeroVector = BABYLON.Vector3.Zero();
  89823. this._lookAtTmpMatrix = new BABYLON.Matrix();
  89824. /* Does nothing */
  89825. }
  89826. /**
  89827. * Initializes the behavior
  89828. */
  89829. AttachToBoxBehavior.prototype.init = function () {
  89830. /* Does nothing */
  89831. };
  89832. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  89833. var _this = this;
  89834. // Go over each face and calculate the angle between the face's normal and targetDirection
  89835. this._faceVectors.forEach(function (v) {
  89836. if (!_this._target.rotationQuaternion) {
  89837. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  89838. }
  89839. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  89840. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  89841. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  89842. });
  89843. // Return the face information of the one with the normal closeset to target direction
  89844. return this._faceVectors.reduce(function (min, p) {
  89845. if (min.ignore) {
  89846. return p;
  89847. }
  89848. else if (p.ignore) {
  89849. return min;
  89850. }
  89851. else {
  89852. return min.diff < p.diff ? min : p;
  89853. }
  89854. }, this._faceVectors[0]);
  89855. };
  89856. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  89857. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  89858. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  89859. this._lookAtTmpMatrix.invert();
  89860. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  89861. };
  89862. /**
  89863. * Attaches the AttachToBoxBehavior to the passed in mesh
  89864. * @param target The mesh that the specified node will be attached to
  89865. */
  89866. AttachToBoxBehavior.prototype.attach = function (target) {
  89867. var _this = this;
  89868. this._target = target;
  89869. this._scene = this._target.getScene();
  89870. // Every frame, update the app bars position
  89871. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89872. if (!_this._scene.activeCamera) {
  89873. return;
  89874. }
  89875. // Find the face closest to the cameras position
  89876. var cameraPos = _this._scene.activeCamera.position;
  89877. if (_this._scene.activeCamera.devicePosition) {
  89878. cameraPos = _this._scene.activeCamera.devicePosition;
  89879. }
  89880. var facing = _this._closestFace(cameraPos.subtract(target.position));
  89881. if (_this._scene.activeCamera.leftCamera) {
  89882. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89883. }
  89884. else {
  89885. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89886. }
  89887. // Get camera up direction
  89888. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  89889. // Ignore faces to not select a parrelel face for the up vector of the UI
  89890. _this._faceVectors.forEach(function (v) {
  89891. if (facing.direction.x && v.direction.x) {
  89892. v.ignore = true;
  89893. }
  89894. if (facing.direction.y && v.direction.y) {
  89895. v.ignore = true;
  89896. }
  89897. if (facing.direction.z && v.direction.z) {
  89898. v.ignore = true;
  89899. }
  89900. });
  89901. var facingUp = _this._closestFace(_this._tmpVector);
  89902. // Unignore faces
  89903. _this._faceVectors.forEach(function (v) {
  89904. v.ignore = false;
  89905. });
  89906. // Position the app bar on that face
  89907. _this.ui.position.copyFrom(target.position);
  89908. if (facing.direction.x) {
  89909. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89910. _this.ui.position.addInPlace(_this._tmpVector);
  89911. }
  89912. if (facing.direction.y) {
  89913. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89914. _this.ui.position.addInPlace(_this._tmpVector);
  89915. }
  89916. if (facing.direction.z) {
  89917. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89918. _this.ui.position.addInPlace(_this._tmpVector);
  89919. }
  89920. // Rotate to be oriented properly to the camera
  89921. if (!_this.ui.rotationQuaternion) {
  89922. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  89923. }
  89924. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  89925. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  89926. // Place ui the correct distance from the bottom of the mesh
  89927. if (facingUp.direction.x) {
  89928. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  89929. }
  89930. if (facingUp.direction.y) {
  89931. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  89932. }
  89933. if (facingUp.direction.z) {
  89934. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  89935. }
  89936. _this.ui.position.addInPlace(_this._tmpVector);
  89937. });
  89938. };
  89939. /**
  89940. * Detaches the behavior from the mesh
  89941. */
  89942. AttachToBoxBehavior.prototype.detach = function () {
  89943. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  89944. };
  89945. return AttachToBoxBehavior;
  89946. }());
  89947. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  89948. })(BABYLON || (BABYLON = {}));
  89949. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  89950. var BABYLON;
  89951. (function (BABYLON) {
  89952. /**
  89953. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89954. */
  89955. var Gizmo = /** @class */ (function () {
  89956. /**
  89957. * Creates a gizmo
  89958. * @param gizmoLayer The utility layer the gizmo will be added to
  89959. */
  89960. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89961. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89962. var _this = this;
  89963. this.gizmoLayer = gizmoLayer;
  89964. this._scaleFactor = 3;
  89965. this._tmpMatrix = new BABYLON.Matrix();
  89966. /**
  89967. * If a custom mesh has been set (Default: false)
  89968. */
  89969. this._customMeshSet = false;
  89970. /**
  89971. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89972. */
  89973. this.updateGizmoRotationToMatchAttachedMesh = true;
  89974. /**
  89975. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89976. */
  89977. this.updateGizmoPositionToMatchAttachedMesh = true;
  89978. /**
  89979. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89980. */
  89981. this._updateScale = true;
  89982. this._interactionsEnabled = true;
  89983. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89984. var tempVector = new BABYLON.Vector3();
  89985. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89986. if (_this.attachedMesh) {
  89987. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89988. if (!_this._rootMesh.rotationQuaternion) {
  89989. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89990. }
  89991. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89992. tempVector.copyFrom(_this.attachedMesh.scaling);
  89993. if (_this.attachedMesh.scaling.x < 0) {
  89994. _this.attachedMesh.scaling.x *= -1;
  89995. }
  89996. if (_this.attachedMesh.scaling.y < 0) {
  89997. _this.attachedMesh.scaling.y *= -1;
  89998. }
  89999. if (_this.attachedMesh.scaling.z < 0) {
  90000. _this.attachedMesh.scaling.z *= -1;
  90001. }
  90002. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  90003. _this.attachedMesh.scaling.copyFrom(tempVector);
  90004. _this.attachedMesh.computeWorldMatrix();
  90005. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  90006. }
  90007. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  90008. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  90009. }
  90010. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  90011. var cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.position;
  90012. if (_this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  90013. cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  90014. }
  90015. _this._rootMesh.position.subtractToRef(cameraPosition, tempVector);
  90016. var dist = tempVector.length() / _this._scaleFactor;
  90017. _this._rootMesh.scaling.set(dist, dist, dist);
  90018. }
  90019. }
  90020. });
  90021. this.attachedMesh = null;
  90022. }
  90023. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  90024. /**
  90025. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  90026. * * When set, interactions will be enabled
  90027. */
  90028. get: function () {
  90029. return this._attachedMesh;
  90030. },
  90031. set: function (value) {
  90032. this._attachedMesh = value;
  90033. this._rootMesh.setEnabled(value ? true : false);
  90034. this._attachedMeshChanged(value);
  90035. },
  90036. enumerable: true,
  90037. configurable: true
  90038. });
  90039. /**
  90040. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  90041. * @param mesh The mesh to replace the default mesh of the gizmo
  90042. */
  90043. Gizmo.prototype.setCustomMesh = function (mesh) {
  90044. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  90045. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  90046. }
  90047. this._rootMesh.getChildMeshes().forEach(function (c) {
  90048. c.dispose();
  90049. });
  90050. mesh.parent = this._rootMesh;
  90051. this._customMeshSet = true;
  90052. };
  90053. Gizmo.prototype._attachedMeshChanged = function (value) {
  90054. };
  90055. /**
  90056. * Disposes of the gizmo
  90057. */
  90058. Gizmo.prototype.dispose = function () {
  90059. this._rootMesh.dispose();
  90060. if (this._beforeRenderObserver) {
  90061. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90062. }
  90063. };
  90064. return Gizmo;
  90065. }());
  90066. BABYLON.Gizmo = Gizmo;
  90067. })(BABYLON || (BABYLON = {}));
  90068. //# sourceMappingURL=babylon.gizmo.js.map
  90069. var BABYLON;
  90070. (function (BABYLON) {
  90071. /**
  90072. * Single axis drag gizmo
  90073. */
  90074. var AxisDragGizmo = /** @class */ (function (_super) {
  90075. __extends(AxisDragGizmo, _super);
  90076. /**
  90077. * Creates an AxisDragGizmo
  90078. * @param gizmoLayer The utility layer the gizmo will be added to
  90079. * @param dragAxis The axis which the gizmo will be able to drag on
  90080. * @param color The color of the gizmo
  90081. */
  90082. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  90083. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90084. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90085. var _this = _super.call(this, gizmoLayer) || this;
  90086. _this._pointerObserver = null;
  90087. /**
  90088. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90089. */
  90090. _this.snapDistance = 0;
  90091. /**
  90092. * Event that fires each time the gizmo snaps to a new location.
  90093. * * snapDistance is the the change in distance
  90094. */
  90095. _this.onSnapObservable = new BABYLON.Observable();
  90096. // Create Material
  90097. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90098. coloredMaterial.disableLighting = true;
  90099. coloredMaterial.emissiveColor = color;
  90100. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90101. hoverMaterial.disableLighting = true;
  90102. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90103. // Build mesh on root node
  90104. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90105. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90106. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90107. arrow.addChild(arrowMesh);
  90108. arrow.addChild(arrowTail);
  90109. // Position arrow pointing in its drag axis
  90110. arrowMesh.scaling.scaleInPlace(0.05);
  90111. arrowMesh.material = coloredMaterial;
  90112. arrowMesh.rotation.x = Math.PI / 2;
  90113. arrowMesh.position.z += 0.3;
  90114. arrowTail.rotation.x = Math.PI / 2;
  90115. arrowTail.material = coloredMaterial;
  90116. arrowTail.position.z += 0.15;
  90117. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90118. _this._rootMesh.addChild(arrow);
  90119. var currentSnapDragDistance = 0;
  90120. var tmpVector = new BABYLON.Vector3();
  90121. var tmpSnapEvent = { snapDistance: 0 };
  90122. // Add drag behavior to handle events when the gizmo is dragged
  90123. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90124. _this.dragBehavior.moveAttached = false;
  90125. _this._rootMesh.addBehavior(_this.dragBehavior);
  90126. _this.dragBehavior.onDragObservable.add(function (event) {
  90127. if (_this.attachedMesh) {
  90128. // Snapping logic
  90129. if (_this.snapDistance == 0) {
  90130. _this.attachedMesh.position.addInPlace(event.delta);
  90131. }
  90132. else {
  90133. currentSnapDragDistance += event.dragDistance;
  90134. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90135. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  90136. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90137. event.delta.normalizeToRef(tmpVector);
  90138. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  90139. _this.attachedMesh.position.addInPlace(tmpVector);
  90140. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90141. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90142. }
  90143. }
  90144. }
  90145. });
  90146. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90147. if (_this._customMeshSet) {
  90148. return;
  90149. }
  90150. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90151. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90152. m.material = hoverMaterial;
  90153. });
  90154. }
  90155. else {
  90156. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90157. m.material = coloredMaterial;
  90158. });
  90159. }
  90160. });
  90161. return _this;
  90162. }
  90163. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  90164. if (this.dragBehavior) {
  90165. this.dragBehavior.enabled = value ? true : false;
  90166. }
  90167. };
  90168. /**
  90169. * Disposes of the gizmo
  90170. */
  90171. AxisDragGizmo.prototype.dispose = function () {
  90172. this.onSnapObservable.clear();
  90173. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90174. this.dragBehavior.detach();
  90175. _super.prototype.dispose.call(this);
  90176. };
  90177. return AxisDragGizmo;
  90178. }(BABYLON.Gizmo));
  90179. BABYLON.AxisDragGizmo = AxisDragGizmo;
  90180. })(BABYLON || (BABYLON = {}));
  90181. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  90182. var BABYLON;
  90183. (function (BABYLON) {
  90184. /**
  90185. * Single axis scale gizmo
  90186. */
  90187. var AxisScaleGizmo = /** @class */ (function (_super) {
  90188. __extends(AxisScaleGizmo, _super);
  90189. /**
  90190. * Creates an AxisScaleGizmo
  90191. * @param gizmoLayer The utility layer the gizmo will be added to
  90192. * @param dragAxis The axis which the gizmo will be able to scale on
  90193. * @param color The color of the gizmo
  90194. */
  90195. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  90196. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90197. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90198. var _this = _super.call(this, gizmoLayer) || this;
  90199. _this._pointerObserver = null;
  90200. /**
  90201. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90202. */
  90203. _this.snapDistance = 0;
  90204. /**
  90205. * Event that fires each time the gizmo snaps to a new location.
  90206. * * snapDistance is the the change in distance
  90207. */
  90208. _this.onSnapObservable = new BABYLON.Observable();
  90209. // Create Material
  90210. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90211. coloredMaterial.disableLighting = true;
  90212. coloredMaterial.emissiveColor = color;
  90213. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90214. hoverMaterial.disableLighting = true;
  90215. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90216. // Build mesh on root node
  90217. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90218. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  90219. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90220. arrow.addChild(arrowMesh);
  90221. arrow.addChild(arrowTail);
  90222. // Position arrow pointing in its drag axis
  90223. arrowMesh.scaling.scaleInPlace(0.1);
  90224. arrowMesh.material = coloredMaterial;
  90225. arrowMesh.rotation.x = Math.PI / 2;
  90226. arrowMesh.position.z += 0.3;
  90227. arrowTail.rotation.x = Math.PI / 2;
  90228. arrowTail.material = coloredMaterial;
  90229. arrowTail.position.z += 0.15;
  90230. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90231. _this._rootMesh.addChild(arrow);
  90232. // Add drag behavior to handle events when the gizmo is dragged
  90233. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90234. _this.dragBehavior.moveAttached = false;
  90235. _this._rootMesh.addBehavior(_this.dragBehavior);
  90236. var currentSnapDragDistance = 0;
  90237. var tmpVector = new BABYLON.Vector3();
  90238. var tmpSnapEvent = { snapDistance: 0 };
  90239. _this.dragBehavior.onDragObservable.add(function (event) {
  90240. if (_this.attachedMesh) {
  90241. // Snapping logic
  90242. var snapped = false;
  90243. var dragSteps = 0;
  90244. if (_this.snapDistance == 0) {
  90245. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  90246. }
  90247. else {
  90248. currentSnapDragDistance += event.dragDistance;
  90249. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90250. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90251. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90252. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  90253. snapped = true;
  90254. }
  90255. else {
  90256. tmpVector.scaleInPlace(0);
  90257. }
  90258. }
  90259. _this.attachedMesh.scaling.addInPlace(tmpVector);
  90260. if (snapped) {
  90261. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90262. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90263. }
  90264. }
  90265. });
  90266. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90267. if (_this._customMeshSet) {
  90268. return;
  90269. }
  90270. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90271. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90272. m.material = hoverMaterial;
  90273. });
  90274. }
  90275. else {
  90276. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90277. m.material = coloredMaterial;
  90278. });
  90279. }
  90280. });
  90281. return _this;
  90282. }
  90283. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  90284. if (this.dragBehavior) {
  90285. this.dragBehavior.enabled = value ? true : false;
  90286. }
  90287. };
  90288. /**
  90289. * Disposes of the gizmo
  90290. */
  90291. AxisScaleGizmo.prototype.dispose = function () {
  90292. this.onSnapObservable.clear();
  90293. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90294. this.dragBehavior.detach();
  90295. _super.prototype.dispose.call(this);
  90296. };
  90297. return AxisScaleGizmo;
  90298. }(BABYLON.Gizmo));
  90299. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  90300. })(BABYLON || (BABYLON = {}));
  90301. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  90302. var BABYLON;
  90303. (function (BABYLON) {
  90304. /**
  90305. * Single plane rotation gizmo
  90306. */
  90307. var PlaneRotationGizmo = /** @class */ (function (_super) {
  90308. __extends(PlaneRotationGizmo, _super);
  90309. /**
  90310. * Creates a PlaneRotationGizmo
  90311. * @param gizmoLayer The utility layer the gizmo will be added to
  90312. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  90313. * @param color The color of the gizmo
  90314. */
  90315. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  90316. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90317. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90318. var _this = _super.call(this, gizmoLayer) || this;
  90319. _this._pointerObserver = null;
  90320. /**
  90321. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  90322. */
  90323. _this.snapDistance = 0;
  90324. /**
  90325. * Event that fires each time the gizmo snaps to a new location.
  90326. * * snapDistance is the the change in distance
  90327. */
  90328. _this.onSnapObservable = new BABYLON.Observable();
  90329. // Create Material
  90330. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90331. coloredMaterial.disableLighting = true;
  90332. coloredMaterial.emissiveColor = color;
  90333. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90334. hoverMaterial.disableLighting = true;
  90335. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90336. // Build mesh on root node
  90337. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90338. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  90339. // Position arrow pointing in its drag axis
  90340. rotationMesh.scaling.scaleInPlace(0.1);
  90341. rotationMesh.material = coloredMaterial;
  90342. rotationMesh.rotation.x = Math.PI / 2;
  90343. parentMesh.addChild(rotationMesh);
  90344. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  90345. _this._rootMesh.addChild(parentMesh);
  90346. // Add drag behavior to handle events when the gizmo is dragged
  90347. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  90348. _this.dragBehavior.moveAttached = false;
  90349. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  90350. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  90351. _this._rootMesh.addBehavior(_this.dragBehavior);
  90352. var lastDragPosition = new BABYLON.Vector3();
  90353. _this.dragBehavior.onDragStartObservable.add(function (e) {
  90354. if (_this.attachedMesh) {
  90355. lastDragPosition.copyFrom(e.dragPlanePoint);
  90356. }
  90357. });
  90358. var rotationMatrix = new BABYLON.Matrix();
  90359. var planeNormalTowardsCamera = new BABYLON.Vector3();
  90360. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  90361. var tmpSnapEvent = { snapDistance: 0 };
  90362. var currentSnapDragDistance = 0;
  90363. _this.dragBehavior.onDragObservable.add(function (event) {
  90364. if (_this.attachedMesh) {
  90365. if (!_this.attachedMesh.rotationQuaternion) {
  90366. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90367. }
  90368. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  90369. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  90370. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  90371. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  90372. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  90373. var angle = Math.atan2(cross.length(), dot);
  90374. planeNormalTowardsCamera.copyFrom(planeNormal);
  90375. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  90376. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90377. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  90378. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  90379. }
  90380. // Flip up vector depending on which side the camera is on
  90381. if (gizmoLayer.utilityLayerScene.activeCamera) {
  90382. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  90383. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  90384. planeNormalTowardsCamera.scaleInPlace(-1);
  90385. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  90386. }
  90387. }
  90388. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  90389. if (halfCircleSide)
  90390. angle = -angle;
  90391. // Snapping logic
  90392. var snapped = false;
  90393. if (_this.snapDistance != 0) {
  90394. currentSnapDragDistance += angle;
  90395. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90396. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90397. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90398. angle = _this.snapDistance * dragSteps;
  90399. snapped = true;
  90400. }
  90401. else {
  90402. angle = 0;
  90403. }
  90404. }
  90405. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  90406. var quaternionCoefficient = Math.sin(angle / 2);
  90407. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  90408. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90409. // Rotate selected mesh quaternion over fixed axis
  90410. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  90411. }
  90412. else {
  90413. // Rotate selected mesh quaternion over rotated axis
  90414. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  90415. }
  90416. lastDragPosition.copyFrom(event.dragPlanePoint);
  90417. if (snapped) {
  90418. tmpSnapEvent.snapDistance = angle;
  90419. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90420. }
  90421. }
  90422. });
  90423. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90424. if (_this._customMeshSet) {
  90425. return;
  90426. }
  90427. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90428. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90429. m.material = hoverMaterial;
  90430. });
  90431. }
  90432. else {
  90433. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90434. m.material = coloredMaterial;
  90435. });
  90436. }
  90437. });
  90438. return _this;
  90439. }
  90440. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  90441. if (this.dragBehavior) {
  90442. this.dragBehavior.enabled = value ? true : false;
  90443. }
  90444. };
  90445. /**
  90446. * Disposes of the gizmo
  90447. */
  90448. PlaneRotationGizmo.prototype.dispose = function () {
  90449. this.onSnapObservable.clear();
  90450. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90451. this.dragBehavior.detach();
  90452. _super.prototype.dispose.call(this);
  90453. };
  90454. return PlaneRotationGizmo;
  90455. }(BABYLON.Gizmo));
  90456. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  90457. })(BABYLON || (BABYLON = {}));
  90458. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  90459. var BABYLON;
  90460. (function (BABYLON) {
  90461. /**
  90462. * Gizmo that enables dragging a mesh along 3 axis
  90463. */
  90464. var PositionGizmo = /** @class */ (function (_super) {
  90465. __extends(PositionGizmo, _super);
  90466. /**
  90467. * Creates a PositionGizmo
  90468. * @param gizmoLayer The utility layer the gizmo will be added to
  90469. */
  90470. function PositionGizmo(gizmoLayer) {
  90471. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90472. var _this = _super.call(this, gizmoLayer) || this;
  90473. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90474. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90475. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90476. _this.attachedMesh = null;
  90477. return _this;
  90478. }
  90479. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  90480. set: function (mesh) {
  90481. if (this.xGizmo) {
  90482. this.xGizmo.attachedMesh = mesh;
  90483. this.yGizmo.attachedMesh = mesh;
  90484. this.zGizmo.attachedMesh = mesh;
  90485. }
  90486. },
  90487. enumerable: true,
  90488. configurable: true
  90489. });
  90490. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90491. get: function () {
  90492. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90493. },
  90494. set: function (value) {
  90495. if (this.xGizmo) {
  90496. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90497. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90498. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90499. }
  90500. },
  90501. enumerable: true,
  90502. configurable: true
  90503. });
  90504. /**
  90505. * Disposes of the gizmo
  90506. */
  90507. PositionGizmo.prototype.dispose = function () {
  90508. this.xGizmo.dispose();
  90509. this.yGizmo.dispose();
  90510. this.zGizmo.dispose();
  90511. };
  90512. /**
  90513. * CustomMeshes are not supported by this gizmo
  90514. * @param mesh The mesh to replace the default mesh of the gizmo
  90515. */
  90516. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  90517. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  90518. };
  90519. return PositionGizmo;
  90520. }(BABYLON.Gizmo));
  90521. BABYLON.PositionGizmo = PositionGizmo;
  90522. })(BABYLON || (BABYLON = {}));
  90523. //# sourceMappingURL=babylon.positionGizmo.js.map
  90524. var BABYLON;
  90525. (function (BABYLON) {
  90526. /**
  90527. * Gizmo that enables rotating a mesh along 3 axis
  90528. */
  90529. var RotationGizmo = /** @class */ (function (_super) {
  90530. __extends(RotationGizmo, _super);
  90531. /**
  90532. * Creates a RotationGizmo
  90533. * @param gizmoLayer The utility layer the gizmo will be added to
  90534. */
  90535. function RotationGizmo(gizmoLayer) {
  90536. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90537. var _this = _super.call(this, gizmoLayer) || this;
  90538. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90539. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90540. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90541. _this.attachedMesh = null;
  90542. return _this;
  90543. }
  90544. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  90545. set: function (mesh) {
  90546. if (this.xGizmo) {
  90547. this.xGizmo.attachedMesh = mesh;
  90548. this.yGizmo.attachedMesh = mesh;
  90549. this.zGizmo.attachedMesh = mesh;
  90550. }
  90551. },
  90552. enumerable: true,
  90553. configurable: true
  90554. });
  90555. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90556. get: function () {
  90557. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90558. },
  90559. set: function (value) {
  90560. if (this.xGizmo) {
  90561. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90562. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90563. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90564. }
  90565. },
  90566. enumerable: true,
  90567. configurable: true
  90568. });
  90569. /**
  90570. * Disposes of the gizmo
  90571. */
  90572. RotationGizmo.prototype.dispose = function () {
  90573. this.xGizmo.dispose();
  90574. this.yGizmo.dispose();
  90575. this.zGizmo.dispose();
  90576. };
  90577. /**
  90578. * CustomMeshes are not supported by this gizmo
  90579. * @param mesh The mesh to replace the default mesh of the gizmo
  90580. */
  90581. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  90582. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  90583. };
  90584. return RotationGizmo;
  90585. }(BABYLON.Gizmo));
  90586. BABYLON.RotationGizmo = RotationGizmo;
  90587. })(BABYLON || (BABYLON = {}));
  90588. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90589. var BABYLON;
  90590. (function (BABYLON) {
  90591. /**
  90592. * Gizmo that enables scaling a mesh along 3 axis
  90593. */
  90594. var ScaleGizmo = /** @class */ (function (_super) {
  90595. __extends(ScaleGizmo, _super);
  90596. /**
  90597. * Creates a ScaleGizmo
  90598. * @param gizmoLayer The utility layer the gizmo will be added to
  90599. */
  90600. function ScaleGizmo(gizmoLayer) {
  90601. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90602. var _this = _super.call(this, gizmoLayer) || this;
  90603. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90604. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90605. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90606. _this.attachedMesh = null;
  90607. return _this;
  90608. }
  90609. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90610. set: function (mesh) {
  90611. if (this.xGizmo) {
  90612. this.xGizmo.attachedMesh = mesh;
  90613. this.yGizmo.attachedMesh = mesh;
  90614. this.zGizmo.attachedMesh = mesh;
  90615. }
  90616. },
  90617. enumerable: true,
  90618. configurable: true
  90619. });
  90620. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90621. get: function () {
  90622. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90623. },
  90624. set: function (value) {
  90625. if (this.xGizmo) {
  90626. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90627. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90628. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90629. }
  90630. },
  90631. enumerable: true,
  90632. configurable: true
  90633. });
  90634. /**
  90635. * Disposes of the gizmo
  90636. */
  90637. ScaleGizmo.prototype.dispose = function () {
  90638. this.xGizmo.dispose();
  90639. this.yGizmo.dispose();
  90640. this.zGizmo.dispose();
  90641. };
  90642. return ScaleGizmo;
  90643. }(BABYLON.Gizmo));
  90644. BABYLON.ScaleGizmo = ScaleGizmo;
  90645. })(BABYLON || (BABYLON = {}));
  90646. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90647. var BABYLON;
  90648. (function (BABYLON) {
  90649. /**
  90650. * Bounding box gizmo
  90651. */
  90652. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90653. __extends(BoundingBoxGizmo, _super);
  90654. /**
  90655. * Creates an BoundingBoxGizmo
  90656. * @param gizmoLayer The utility layer the gizmo will be added to
  90657. * @param color The color of the gizmo
  90658. */
  90659. function BoundingBoxGizmo(color, gizmoLayer) {
  90660. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90661. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  90662. var _this = _super.call(this, gizmoLayer) || this;
  90663. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90664. _this._renderObserver = null;
  90665. _this._pointerObserver = null;
  90666. _this._scaleDragSpeed = 0.2;
  90667. _this._tmpQuaternion = new BABYLON.Quaternion();
  90668. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90669. /**
  90670. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90671. */
  90672. _this.rotationSphereSize = 0.1;
  90673. /**
  90674. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90675. */
  90676. _this.scaleBoxSize = 0.1;
  90677. /**
  90678. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  90679. */
  90680. _this.fixedDragMeshScreenSize = false;
  90681. /**
  90682. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90683. */
  90684. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90685. /**
  90686. * Fired when a rotation sphere or scale box is dragged
  90687. */
  90688. _this.onDragStartObservable = new BABYLON.Observable();
  90689. /**
  90690. * Fired when a rotation sphere or scale box drag is started
  90691. */
  90692. _this.onDragObservable = new BABYLON.Observable();
  90693. /**
  90694. * Fired when a rotation sphere or scale box drag is needed
  90695. */
  90696. _this.onDragEndObservable = new BABYLON.Observable();
  90697. _this._existingMeshScale = new BABYLON.Vector3();
  90698. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90699. _this._updateScale = false;
  90700. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  90701. // Create Materials
  90702. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90703. coloredMaterial.disableLighting = true;
  90704. coloredMaterial.emissiveColor = color;
  90705. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90706. hoverColoredMaterial.disableLighting = true;
  90707. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90708. // Build bounding box out of lines
  90709. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90710. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90711. var lines = [];
  90712. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90713. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90714. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90715. 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));
  90716. 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));
  90717. 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));
  90718. 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));
  90719. 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));
  90720. 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));
  90721. 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));
  90722. 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));
  90723. 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));
  90724. lines.forEach(function (l) {
  90725. l.color = color;
  90726. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90727. l.isPickable = false;
  90728. _this._lineBoundingBox.addChild(l);
  90729. });
  90730. _this._rootMesh.addChild(_this._lineBoundingBox);
  90731. // Create rotation spheres
  90732. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90733. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90734. var _loop_1 = function (i_1) {
  90735. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90736. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90737. sphere.material = coloredMaterial;
  90738. // Drag behavior
  90739. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90740. _dragBehavior.moveAttached = false;
  90741. _dragBehavior.updateDragPlane = false;
  90742. sphere.addBehavior(_dragBehavior);
  90743. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90744. var totalTurnAmountOfDrag = 0;
  90745. _dragBehavior.onDragStartObservable.add(function (event) {
  90746. startingTurnDirection.copyFrom(sphere.forward);
  90747. totalTurnAmountOfDrag = 0;
  90748. });
  90749. _dragBehavior.onDragObservable.add(function (event) {
  90750. _this.onDragObservable.notifyObservers({});
  90751. if (_this.attachedMesh) {
  90752. var worldDragDirection = startingTurnDirection;
  90753. // Project the world right on to the drag plane
  90754. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90755. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90756. // project drag delta on to the resulting drag axis and rotate based on that
  90757. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90758. // Rotate based on axis
  90759. if (!_this.attachedMesh.rotationQuaternion) {
  90760. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90761. }
  90762. if (!_this._anchorMesh.rotationQuaternion) {
  90763. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  90764. }
  90765. // Do not allow the object to turn more than a full circle
  90766. totalTurnAmountOfDrag += projectDist;
  90767. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90768. if (i_1 >= 8) {
  90769. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90770. }
  90771. else if (i_1 >= 4) {
  90772. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90773. }
  90774. else {
  90775. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90776. }
  90777. // Rotate around center of bounding box
  90778. _this._anchorMesh.addChild(_this.attachedMesh);
  90779. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  90780. _this._anchorMesh.removeChild(_this.attachedMesh);
  90781. }
  90782. _this.updateBoundingBox();
  90783. }
  90784. });
  90785. // Selection/deselection
  90786. _dragBehavior.onDragStartObservable.add(function () {
  90787. _this.onDragStartObservable.notifyObservers({});
  90788. _this._selectNode(sphere);
  90789. });
  90790. _dragBehavior.onDragEndObservable.add(function () {
  90791. _this.onDragEndObservable.notifyObservers({});
  90792. _this._selectNode(null);
  90793. });
  90794. this_1._rotateSpheresParent.addChild(sphere);
  90795. };
  90796. var this_1 = this, _dragBehavior;
  90797. for (var i_1 = 0; i_1 < 12; i_1++) {
  90798. _loop_1(i_1);
  90799. }
  90800. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90801. // Create scale cubes
  90802. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90803. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90804. for (var i = 0; i < 2; i++) {
  90805. for (var j = 0; j < 2; j++) {
  90806. var _loop_2 = function () {
  90807. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90808. box.material = coloredMaterial;
  90809. // Dragging logic
  90810. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90811. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90812. _dragBehavior.moveAttached = false;
  90813. box.addBehavior(_dragBehavior);
  90814. _dragBehavior.onDragObservable.add(function (event) {
  90815. _this.onDragObservable.notifyObservers({});
  90816. if (_this.attachedMesh) {
  90817. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90818. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90819. _this.updateBoundingBox();
  90820. // Scale from the position of the opposite corner
  90821. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  90822. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  90823. _this._anchorMesh.addChild(_this.attachedMesh);
  90824. _this._anchorMesh.scaling.addInPlace(deltaScale);
  90825. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  90826. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  90827. }
  90828. _this._anchorMesh.removeChild(_this.attachedMesh);
  90829. }
  90830. });
  90831. // Selection/deselection
  90832. _dragBehavior.onDragStartObservable.add(function () {
  90833. _this.onDragStartObservable.notifyObservers({});
  90834. _this._selectNode(box);
  90835. });
  90836. _dragBehavior.onDragEndObservable.add(function () {
  90837. _this.onDragEndObservable.notifyObservers({});
  90838. _this._selectNode(null);
  90839. });
  90840. this_2._scaleBoxesParent.addChild(box);
  90841. };
  90842. var this_2 = this, _dragBehavior;
  90843. for (var k = 0; k < 2; k++) {
  90844. _loop_2();
  90845. }
  90846. }
  90847. }
  90848. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90849. // Hover color change
  90850. var pointerIds = new Array();
  90851. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90852. if (!pointerIds[pointerInfo.event.pointerId]) {
  90853. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90854. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90855. pointerIds[pointerInfo.event.pointerId] = mesh;
  90856. mesh.material = hoverColoredMaterial;
  90857. }
  90858. });
  90859. }
  90860. else {
  90861. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90862. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90863. delete pointerIds[pointerInfo.event.pointerId];
  90864. }
  90865. }
  90866. });
  90867. // Update bounding box positions
  90868. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90869. // Only update the bouding box if scaling has changed
  90870. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  90871. _this.updateBoundingBox();
  90872. }
  90873. });
  90874. _this.updateBoundingBox();
  90875. return _this;
  90876. }
  90877. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  90878. if (value) {
  90879. // Reset anchor mesh to match attached mesh's scale
  90880. // This is needed to avoid invalid box/sphere position on first drag
  90881. this._anchorMesh.addChild(value);
  90882. this._anchorMesh.removeChild(value);
  90883. this.updateBoundingBox();
  90884. }
  90885. };
  90886. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90887. this._rotateSpheresParent.getChildMeshes()
  90888. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90889. m.isVisible = (!selectedMesh || m == selectedMesh);
  90890. });
  90891. };
  90892. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  90893. var _this = this;
  90894. mesh.computeWorldMatrix(true);
  90895. mesh.getChildMeshes().forEach(function (m) {
  90896. _this._recurseComputeWorld(m);
  90897. });
  90898. };
  90899. /**
  90900. * Updates the bounding box information for the Gizmo
  90901. */
  90902. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  90903. if (this.attachedMesh) {
  90904. // Rotate based on axis
  90905. if (!this.attachedMesh.rotationQuaternion) {
  90906. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  90907. }
  90908. if (!this._anchorMesh.rotationQuaternion) {
  90909. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  90910. }
  90911. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90912. // Store original position and reset mesh to origin before computing the bounding box
  90913. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90914. this._tmpVector.copyFrom(this.attachedMesh.position);
  90915. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  90916. this.attachedMesh.position.set(0, 0, 0);
  90917. // Update bounding dimensions/positions
  90918. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  90919. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  90920. // Update gizmo to match bounding box scaling and rotation
  90921. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90922. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  90923. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  90924. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  90925. this._lineBoundingBox.computeWorldMatrix();
  90926. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  90927. // restore position/rotation values
  90928. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  90929. this.attachedMesh.position.copyFrom(this._tmpVector);
  90930. this._recurseComputeWorld(this.attachedMesh);
  90931. }
  90932. // Update rotation sphere locations
  90933. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90934. for (var i = 0; i < 3; i++) {
  90935. for (var j = 0; j < 2; j++) {
  90936. for (var k = 0; k < 2; k++) {
  90937. var index = ((i * 4) + (j * 2)) + k;
  90938. if (i == 0) {
  90939. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90940. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90941. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90942. }
  90943. if (i == 1) {
  90944. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90945. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90946. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90947. }
  90948. if (i == 2) {
  90949. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90950. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90951. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90952. }
  90953. if (this.fixedDragMeshScreenSize) {
  90954. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90955. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90956. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90957. }
  90958. else {
  90959. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90960. }
  90961. }
  90962. }
  90963. }
  90964. // Update scale box locations
  90965. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90966. for (var i = 0; i < 2; i++) {
  90967. for (var j = 0; j < 2; j++) {
  90968. for (var k = 0; k < 2; k++) {
  90969. var index = ((i * 4) + (j * 2)) + k;
  90970. if (scaleBoxes[index]) {
  90971. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90972. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90973. if (this.fixedDragMeshScreenSize) {
  90974. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90975. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90976. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90977. }
  90978. else {
  90979. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90980. }
  90981. }
  90982. }
  90983. }
  90984. }
  90985. if (this.attachedMesh) {
  90986. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  90987. }
  90988. };
  90989. /**
  90990. * Enables rotation on the specified axis and disables rotation on the others
  90991. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90992. */
  90993. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90994. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90995. if (i < 4) {
  90996. m.setEnabled(axis.indexOf("x") != -1);
  90997. }
  90998. else if (i < 8) {
  90999. m.setEnabled(axis.indexOf("y") != -1);
  91000. }
  91001. else {
  91002. m.setEnabled(axis.indexOf("z") != -1);
  91003. }
  91004. });
  91005. };
  91006. /**
  91007. * Disposes of the gizmo
  91008. */
  91009. BoundingBoxGizmo.prototype.dispose = function () {
  91010. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91011. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  91012. this._lineBoundingBox.dispose();
  91013. this._rotateSpheresParent.dispose();
  91014. this._scaleBoxesParent.dispose();
  91015. _super.prototype.dispose.call(this);
  91016. };
  91017. /**
  91018. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  91019. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  91020. * @returns the bounding box mesh with the passed in mesh as a child
  91021. */
  91022. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  91023. var makeNotPickable = function (root) {
  91024. root.isPickable = false;
  91025. root.getChildMeshes().forEach(function (c) {
  91026. makeNotPickable(c);
  91027. });
  91028. };
  91029. makeNotPickable(mesh);
  91030. // Reset position to get boudning box from origin with no rotation
  91031. if (!mesh.rotationQuaternion) {
  91032. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  91033. }
  91034. var oldPos = mesh.position.clone();
  91035. var oldRot = mesh.rotationQuaternion.clone();
  91036. mesh.rotationQuaternion.set(0, 0, 0, 1);
  91037. mesh.position.set(0, 0, 0);
  91038. // Update bounding dimensions/positions
  91039. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  91040. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  91041. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  91042. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  91043. // Restore original positions
  91044. mesh.addChild(box);
  91045. mesh.rotationQuaternion.copyFrom(oldRot);
  91046. mesh.position.copyFrom(oldPos);
  91047. // Reverse parenting
  91048. mesh.removeChild(box);
  91049. box.addChild(mesh);
  91050. box.visibility = 0;
  91051. return box;
  91052. };
  91053. /**
  91054. * CustomMeshes are not supported by this gizmo
  91055. * @param mesh The mesh to replace the default mesh of the gizmo
  91056. */
  91057. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  91058. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  91059. };
  91060. return BoundingBoxGizmo;
  91061. }(BABYLON.Gizmo));
  91062. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  91063. })(BABYLON || (BABYLON = {}));
  91064. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  91065. var BABYLON;
  91066. (function (BABYLON) {
  91067. /**
  91068. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  91069. */
  91070. var GizmoManager = /** @class */ (function () {
  91071. /**
  91072. * Instatiates a gizmo manager
  91073. * @param scene the scene to overlay the gizmos on top of
  91074. */
  91075. function GizmoManager(scene) {
  91076. var _this = this;
  91077. this.scene = scene;
  91078. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  91079. this._pointerObserver = null;
  91080. this._attachedMesh = null;
  91081. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  91082. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  91083. /**
  91084. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  91085. */
  91086. this.attachableMeshes = null;
  91087. /**
  91088. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  91089. */
  91090. this.usePointerToAttachGizmos = true;
  91091. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  91092. // Instatiate/dispose gizmos based on pointer actions
  91093. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  91094. if (!_this.usePointerToAttachGizmos) {
  91095. return;
  91096. }
  91097. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91098. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  91099. var node = pointerInfo.pickInfo.pickedMesh;
  91100. if (_this.attachableMeshes == null) {
  91101. // Attach to the most parent node
  91102. while (node && node.parent != null) {
  91103. node = node.parent;
  91104. }
  91105. }
  91106. else {
  91107. // Attach to the parent node that is an attachableMesh
  91108. var found = false;
  91109. _this.attachableMeshes.forEach(function (mesh) {
  91110. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  91111. node = mesh;
  91112. found = true;
  91113. }
  91114. });
  91115. if (!found) {
  91116. node = null;
  91117. }
  91118. }
  91119. if (node instanceof BABYLON.AbstractMesh) {
  91120. _this.attachToMesh(node);
  91121. }
  91122. }
  91123. else {
  91124. _this.attachToMesh(null);
  91125. }
  91126. }
  91127. });
  91128. }
  91129. /**
  91130. * Attaches a set of gizmos to the specified mesh
  91131. * @param mesh The mesh the gizmo's should be attached to
  91132. */
  91133. GizmoManager.prototype.attachToMesh = function (mesh) {
  91134. if (this._attachedMesh) {
  91135. this._attachedMesh.removeBehavior(this._dragBehavior);
  91136. }
  91137. this._attachedMesh = mesh;
  91138. for (var key in this.gizmos) {
  91139. var gizmo = (this.gizmos[key]);
  91140. if (gizmo && this._gizmosEnabled[key]) {
  91141. gizmo.attachedMesh = mesh;
  91142. }
  91143. }
  91144. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  91145. this._attachedMesh.addBehavior(this._dragBehavior);
  91146. }
  91147. };
  91148. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  91149. get: function () {
  91150. return this._gizmosEnabled.positionGizmo;
  91151. },
  91152. /**
  91153. * If the position gizmo is enabled
  91154. */
  91155. set: function (value) {
  91156. if (value) {
  91157. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  91158. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91159. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  91160. }
  91161. else if (this.gizmos.positionGizmo) {
  91162. this.gizmos.positionGizmo.attachedMesh = null;
  91163. }
  91164. this._gizmosEnabled.positionGizmo = value;
  91165. },
  91166. enumerable: true,
  91167. configurable: true
  91168. });
  91169. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  91170. get: function () {
  91171. return this._gizmosEnabled.rotationGizmo;
  91172. },
  91173. /**
  91174. * If the rotation gizmo is enabled
  91175. */
  91176. set: function (value) {
  91177. if (value) {
  91178. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  91179. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91180. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  91181. }
  91182. else if (this.gizmos.rotationGizmo) {
  91183. this.gizmos.rotationGizmo.attachedMesh = null;
  91184. }
  91185. this._gizmosEnabled.rotationGizmo = value;
  91186. },
  91187. enumerable: true,
  91188. configurable: true
  91189. });
  91190. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  91191. get: function () {
  91192. return this._gizmosEnabled.scaleGizmo;
  91193. },
  91194. /**
  91195. * If the scale gizmo is enabled
  91196. */
  91197. set: function (value) {
  91198. if (value) {
  91199. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  91200. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  91201. }
  91202. else if (this.gizmos.scaleGizmo) {
  91203. this.gizmos.scaleGizmo.attachedMesh = null;
  91204. }
  91205. this._gizmosEnabled.scaleGizmo = value;
  91206. },
  91207. enumerable: true,
  91208. configurable: true
  91209. });
  91210. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  91211. get: function () {
  91212. return this._gizmosEnabled.boundingBoxGizmo;
  91213. },
  91214. /**
  91215. * If the boundingBox gizmo is enabled
  91216. */
  91217. set: function (value) {
  91218. if (value) {
  91219. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  91220. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  91221. if (this._attachedMesh) {
  91222. this._attachedMesh.removeBehavior(this._dragBehavior);
  91223. this._attachedMesh.addBehavior(this._dragBehavior);
  91224. }
  91225. }
  91226. else if (this.gizmos.boundingBoxGizmo) {
  91227. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  91228. }
  91229. this._gizmosEnabled.boundingBoxGizmo = value;
  91230. },
  91231. enumerable: true,
  91232. configurable: true
  91233. });
  91234. /**
  91235. * Disposes of the gizmo manager
  91236. */
  91237. GizmoManager.prototype.dispose = function () {
  91238. this.scene.onPointerObservable.remove(this._pointerObserver);
  91239. for (var key in this.gizmos) {
  91240. var gizmo = (this.gizmos[key]);
  91241. if (gizmo) {
  91242. gizmo.dispose();
  91243. }
  91244. }
  91245. this._gizmoLayer.dispose();
  91246. };
  91247. return GizmoManager;
  91248. }());
  91249. BABYLON.GizmoManager = GizmoManager;
  91250. })(BABYLON || (BABYLON = {}));
  91251. //# sourceMappingURL=babylon.gizmoManager.js.map
  91252. var BABYLON;
  91253. (function (BABYLON) {
  91254. /**
  91255. * Defines a target to use with MorphTargetManager
  91256. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91257. */
  91258. var MorphTarget = /** @class */ (function () {
  91259. /**
  91260. * Creates a new MorphTarget
  91261. * @param name defines the name of the target
  91262. * @param influence defines the influence to use
  91263. */
  91264. function MorphTarget(
  91265. /** defines the name of the target */
  91266. name, influence, scene) {
  91267. if (influence === void 0) { influence = 0; }
  91268. if (scene === void 0) { scene = null; }
  91269. this.name = name;
  91270. /**
  91271. * Gets or sets the list of animations
  91272. */
  91273. this.animations = new Array();
  91274. this._positions = null;
  91275. this._normals = null;
  91276. this._tangents = null;
  91277. /**
  91278. * Observable raised when the influence changes
  91279. */
  91280. this.onInfluenceChanged = new BABYLON.Observable();
  91281. this._animationPropertiesOverride = null;
  91282. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91283. this.influence = influence;
  91284. }
  91285. Object.defineProperty(MorphTarget.prototype, "influence", {
  91286. /**
  91287. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  91288. */
  91289. get: function () {
  91290. return this._influence;
  91291. },
  91292. set: function (influence) {
  91293. if (this._influence === influence) {
  91294. return;
  91295. }
  91296. var previous = this._influence;
  91297. this._influence = influence;
  91298. if (this.onInfluenceChanged.hasObservers) {
  91299. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  91300. }
  91301. },
  91302. enumerable: true,
  91303. configurable: true
  91304. });
  91305. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  91306. /**
  91307. * Gets or sets the animation properties override
  91308. */
  91309. get: function () {
  91310. if (!this._animationPropertiesOverride && this._scene) {
  91311. return this._scene.animationPropertiesOverride;
  91312. }
  91313. return this._animationPropertiesOverride;
  91314. },
  91315. set: function (value) {
  91316. this._animationPropertiesOverride = value;
  91317. },
  91318. enumerable: true,
  91319. configurable: true
  91320. });
  91321. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  91322. /**
  91323. * Gets a boolean defining if the target contains position data
  91324. */
  91325. get: function () {
  91326. return !!this._positions;
  91327. },
  91328. enumerable: true,
  91329. configurable: true
  91330. });
  91331. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  91332. /**
  91333. * Gets a boolean defining if the target contains normal data
  91334. */
  91335. get: function () {
  91336. return !!this._normals;
  91337. },
  91338. enumerable: true,
  91339. configurable: true
  91340. });
  91341. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  91342. /**
  91343. * Gets a boolean defining if the target contains tangent data
  91344. */
  91345. get: function () {
  91346. return !!this._tangents;
  91347. },
  91348. enumerable: true,
  91349. configurable: true
  91350. });
  91351. /**
  91352. * Affects position data to this target
  91353. * @param data defines the position data to use
  91354. */
  91355. MorphTarget.prototype.setPositions = function (data) {
  91356. this._positions = data;
  91357. };
  91358. /**
  91359. * Gets the position data stored in this target
  91360. * @returns a FloatArray containing the position data (or null if not present)
  91361. */
  91362. MorphTarget.prototype.getPositions = function () {
  91363. return this._positions;
  91364. };
  91365. /**
  91366. * Affects normal data to this target
  91367. * @param data defines the normal data to use
  91368. */
  91369. MorphTarget.prototype.setNormals = function (data) {
  91370. this._normals = data;
  91371. };
  91372. /**
  91373. * Gets the normal data stored in this target
  91374. * @returns a FloatArray containing the normal data (or null if not present)
  91375. */
  91376. MorphTarget.prototype.getNormals = function () {
  91377. return this._normals;
  91378. };
  91379. /**
  91380. * Affects tangent data to this target
  91381. * @param data defines the tangent data to use
  91382. */
  91383. MorphTarget.prototype.setTangents = function (data) {
  91384. this._tangents = data;
  91385. };
  91386. /**
  91387. * Gets the tangent data stored in this target
  91388. * @returns a FloatArray containing the tangent data (or null if not present)
  91389. */
  91390. MorphTarget.prototype.getTangents = function () {
  91391. return this._tangents;
  91392. };
  91393. /**
  91394. * Serializes the current target into a Serialization object
  91395. * @returns the serialized object
  91396. */
  91397. MorphTarget.prototype.serialize = function () {
  91398. var serializationObject = {};
  91399. serializationObject.name = this.name;
  91400. serializationObject.influence = this.influence;
  91401. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  91402. if (this.hasNormals) {
  91403. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  91404. }
  91405. if (this.hasTangents) {
  91406. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  91407. }
  91408. // Animations
  91409. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  91410. return serializationObject;
  91411. };
  91412. // Statics
  91413. /**
  91414. * Creates a new target from serialized data
  91415. * @param serializationObject defines the serialized data to use
  91416. * @returns a new MorphTarget
  91417. */
  91418. MorphTarget.Parse = function (serializationObject) {
  91419. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  91420. result.setPositions(serializationObject.positions);
  91421. if (serializationObject.normals) {
  91422. result.setNormals(serializationObject.normals);
  91423. }
  91424. if (serializationObject.tangents) {
  91425. result.setTangents(serializationObject.tangents);
  91426. }
  91427. // Animations
  91428. if (serializationObject.animations) {
  91429. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  91430. var parsedAnimation = serializationObject.animations[animationIndex];
  91431. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  91432. }
  91433. }
  91434. return result;
  91435. };
  91436. /**
  91437. * Creates a MorphTarget from mesh data
  91438. * @param mesh defines the source mesh
  91439. * @param name defines the name to use for the new target
  91440. * @param influence defines the influence to attach to the target
  91441. * @returns a new MorphTarget
  91442. */
  91443. MorphTarget.FromMesh = function (mesh, name, influence) {
  91444. if (!name) {
  91445. name = mesh.name;
  91446. }
  91447. var result = new MorphTarget(name, influence, mesh.getScene());
  91448. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91450. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  91451. }
  91452. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  91453. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  91454. }
  91455. return result;
  91456. };
  91457. return MorphTarget;
  91458. }());
  91459. BABYLON.MorphTarget = MorphTarget;
  91460. })(BABYLON || (BABYLON = {}));
  91461. //# sourceMappingURL=babylon.morphTarget.js.map
  91462. var BABYLON;
  91463. (function (BABYLON) {
  91464. /**
  91465. * This class is used to deform meshes using morphing between different targets
  91466. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91467. */
  91468. var MorphTargetManager = /** @class */ (function () {
  91469. /**
  91470. * Creates a new MorphTargetManager
  91471. * @param scene defines the current scene
  91472. */
  91473. function MorphTargetManager(scene) {
  91474. if (scene === void 0) { scene = null; }
  91475. this._targets = new Array();
  91476. this._targetObservable = new Array();
  91477. this._activeTargets = new BABYLON.SmartArray(16);
  91478. this._supportsNormals = false;
  91479. this._supportsTangents = false;
  91480. this._vertexCount = 0;
  91481. this._uniqueId = 0;
  91482. this._tempInfluences = new Array();
  91483. if (!scene) {
  91484. scene = BABYLON.Engine.LastCreatedScene;
  91485. }
  91486. this._scene = scene;
  91487. if (this._scene) {
  91488. this._scene.morphTargetManagers.push(this);
  91489. this._uniqueId = this._scene.getUniqueId();
  91490. }
  91491. }
  91492. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  91493. /**
  91494. * Gets the unique ID of this manager
  91495. */
  91496. get: function () {
  91497. return this._uniqueId;
  91498. },
  91499. enumerable: true,
  91500. configurable: true
  91501. });
  91502. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  91503. /**
  91504. * Gets the number of vertices handled by this manager
  91505. */
  91506. get: function () {
  91507. return this._vertexCount;
  91508. },
  91509. enumerable: true,
  91510. configurable: true
  91511. });
  91512. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  91513. /**
  91514. * Gets a boolean indicating if this manager supports morphing of normals
  91515. */
  91516. get: function () {
  91517. return this._supportsNormals;
  91518. },
  91519. enumerable: true,
  91520. configurable: true
  91521. });
  91522. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  91523. /**
  91524. * Gets a boolean indicating if this manager supports morphing of tangents
  91525. */
  91526. get: function () {
  91527. return this._supportsTangents;
  91528. },
  91529. enumerable: true,
  91530. configurable: true
  91531. });
  91532. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  91533. /**
  91534. * Gets the number of targets stored in this manager
  91535. */
  91536. get: function () {
  91537. return this._targets.length;
  91538. },
  91539. enumerable: true,
  91540. configurable: true
  91541. });
  91542. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  91543. /**
  91544. * Gets the number of influencers (ie. the number of targets with influences > 0)
  91545. */
  91546. get: function () {
  91547. return this._activeTargets.length;
  91548. },
  91549. enumerable: true,
  91550. configurable: true
  91551. });
  91552. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  91553. /**
  91554. * Gets the list of influences (one per target)
  91555. */
  91556. get: function () {
  91557. return this._influences;
  91558. },
  91559. enumerable: true,
  91560. configurable: true
  91561. });
  91562. /**
  91563. * Gets the active target at specified index. An active target is a target with an influence > 0
  91564. * @param index defines the index to check
  91565. * @returns the requested target
  91566. */
  91567. MorphTargetManager.prototype.getActiveTarget = function (index) {
  91568. return this._activeTargets.data[index];
  91569. };
  91570. /**
  91571. * Gets the target at specified index
  91572. * @param index defines the index to check
  91573. * @returns the requested target
  91574. */
  91575. MorphTargetManager.prototype.getTarget = function (index) {
  91576. return this._targets[index];
  91577. };
  91578. /**
  91579. * Add a new target to this manager
  91580. * @param target defines the target to add
  91581. */
  91582. MorphTargetManager.prototype.addTarget = function (target) {
  91583. var _this = this;
  91584. this._targets.push(target);
  91585. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  91586. _this._syncActiveTargets(needUpdate);
  91587. }));
  91588. this._syncActiveTargets(true);
  91589. };
  91590. /**
  91591. * Removes a target from the manager
  91592. * @param target defines the target to remove
  91593. */
  91594. MorphTargetManager.prototype.removeTarget = function (target) {
  91595. var index = this._targets.indexOf(target);
  91596. if (index >= 0) {
  91597. this._targets.splice(index, 1);
  91598. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  91599. this._syncActiveTargets(true);
  91600. }
  91601. };
  91602. /**
  91603. * Serializes the current manager into a Serialization object
  91604. * @returns the serialized object
  91605. */
  91606. MorphTargetManager.prototype.serialize = function () {
  91607. var serializationObject = {};
  91608. serializationObject.id = this.uniqueId;
  91609. serializationObject.targets = [];
  91610. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91611. var target = _a[_i];
  91612. serializationObject.targets.push(target.serialize());
  91613. }
  91614. return serializationObject;
  91615. };
  91616. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  91617. var influenceCount = 0;
  91618. this._activeTargets.reset();
  91619. this._supportsNormals = true;
  91620. this._supportsTangents = true;
  91621. this._vertexCount = 0;
  91622. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91623. var target = _a[_i];
  91624. this._activeTargets.push(target);
  91625. this._tempInfluences[influenceCount++] = target.influence;
  91626. var positions = target.getPositions();
  91627. if (positions) {
  91628. this._supportsNormals = this._supportsNormals && target.hasNormals;
  91629. this._supportsTangents = this._supportsTangents && target.hasTangents;
  91630. var vertexCount = positions.length / 3;
  91631. if (this._vertexCount === 0) {
  91632. this._vertexCount = vertexCount;
  91633. }
  91634. else if (this._vertexCount !== vertexCount) {
  91635. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  91636. return;
  91637. }
  91638. }
  91639. }
  91640. if (!this._influences || this._influences.length !== influenceCount) {
  91641. this._influences = new Float32Array(influenceCount);
  91642. }
  91643. for (var index = 0; index < influenceCount; index++) {
  91644. this._influences[index] = this._tempInfluences[index];
  91645. }
  91646. if (needUpdate) {
  91647. this.synchronize();
  91648. }
  91649. };
  91650. /**
  91651. * Syncrhonize the targets with all the meshes using this morph target manager
  91652. */
  91653. MorphTargetManager.prototype.synchronize = function () {
  91654. if (!this._scene) {
  91655. return;
  91656. }
  91657. // Flag meshes as dirty to resync with the active targets
  91658. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  91659. var mesh = _a[_i];
  91660. if (mesh.morphTargetManager === this) {
  91661. mesh._syncGeometryWithMorphTargetManager();
  91662. }
  91663. }
  91664. };
  91665. // Statics
  91666. /**
  91667. * Creates a new MorphTargetManager from serialized data
  91668. * @param serializationObject defines the serialized data
  91669. * @param scene defines the hosting scene
  91670. * @returns the new MorphTargetManager
  91671. */
  91672. MorphTargetManager.Parse = function (serializationObject, scene) {
  91673. var result = new MorphTargetManager(scene);
  91674. result._uniqueId = serializationObject.id;
  91675. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  91676. var targetData = _a[_i];
  91677. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  91678. }
  91679. return result;
  91680. };
  91681. return MorphTargetManager;
  91682. }());
  91683. BABYLON.MorphTargetManager = MorphTargetManager;
  91684. })(BABYLON || (BABYLON = {}));
  91685. //# sourceMappingURL=babylon.morphTargetManager.js.map
  91686. var BABYLON;
  91687. (function (BABYLON) {
  91688. var Octree = /** @class */ (function () {
  91689. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  91690. if (maxDepth === void 0) { maxDepth = 2; }
  91691. this.maxDepth = maxDepth;
  91692. this.dynamicContent = new Array();
  91693. this._maxBlockCapacity = maxBlockCapacity || 64;
  91694. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  91695. this._creationFunc = creationFunc;
  91696. }
  91697. // Methods
  91698. Octree.prototype.update = function (worldMin, worldMax, entries) {
  91699. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  91700. };
  91701. Octree.prototype.addMesh = function (entry) {
  91702. for (var index = 0; index < this.blocks.length; index++) {
  91703. var block = this.blocks[index];
  91704. block.addEntry(entry);
  91705. }
  91706. };
  91707. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  91708. this._selectionContent.reset();
  91709. for (var index = 0; index < this.blocks.length; index++) {
  91710. var block = this.blocks[index];
  91711. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  91712. }
  91713. if (allowDuplicate) {
  91714. this._selectionContent.concat(this.dynamicContent);
  91715. }
  91716. else {
  91717. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91718. }
  91719. return this._selectionContent;
  91720. };
  91721. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  91722. this._selectionContent.reset();
  91723. for (var index = 0; index < this.blocks.length; index++) {
  91724. var block = this.blocks[index];
  91725. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91726. }
  91727. if (allowDuplicate) {
  91728. this._selectionContent.concat(this.dynamicContent);
  91729. }
  91730. else {
  91731. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91732. }
  91733. return this._selectionContent;
  91734. };
  91735. Octree.prototype.intersectsRay = function (ray) {
  91736. this._selectionContent.reset();
  91737. for (var index = 0; index < this.blocks.length; index++) {
  91738. var block = this.blocks[index];
  91739. block.intersectsRay(ray, this._selectionContent);
  91740. }
  91741. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91742. return this._selectionContent;
  91743. };
  91744. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91745. target.blocks = new Array();
  91746. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91747. // Segmenting space
  91748. for (var x = 0; x < 2; x++) {
  91749. for (var y = 0; y < 2; y++) {
  91750. for (var z = 0; z < 2; z++) {
  91751. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91752. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91753. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91754. block.addEntries(entries);
  91755. target.blocks.push(block);
  91756. }
  91757. }
  91758. }
  91759. };
  91760. Octree.CreationFuncForMeshes = function (entry, block) {
  91761. var boundingInfo = entry.getBoundingInfo();
  91762. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91763. block.entries.push(entry);
  91764. }
  91765. };
  91766. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91767. var boundingInfo = entry.getBoundingInfo();
  91768. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91769. block.entries.push(entry);
  91770. }
  91771. };
  91772. return Octree;
  91773. }());
  91774. BABYLON.Octree = Octree;
  91775. })(BABYLON || (BABYLON = {}));
  91776. //# sourceMappingURL=babylon.octree.js.map
  91777. var BABYLON;
  91778. (function (BABYLON) {
  91779. var OctreeBlock = /** @class */ (function () {
  91780. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91781. this.entries = new Array();
  91782. this._boundingVectors = new Array();
  91783. this._capacity = capacity;
  91784. this._depth = depth;
  91785. this._maxDepth = maxDepth;
  91786. this._creationFunc = creationFunc;
  91787. this._minPoint = minPoint;
  91788. this._maxPoint = maxPoint;
  91789. this._boundingVectors.push(minPoint.clone());
  91790. this._boundingVectors.push(maxPoint.clone());
  91791. this._boundingVectors.push(minPoint.clone());
  91792. this._boundingVectors[2].x = maxPoint.x;
  91793. this._boundingVectors.push(minPoint.clone());
  91794. this._boundingVectors[3].y = maxPoint.y;
  91795. this._boundingVectors.push(minPoint.clone());
  91796. this._boundingVectors[4].z = maxPoint.z;
  91797. this._boundingVectors.push(maxPoint.clone());
  91798. this._boundingVectors[5].z = minPoint.z;
  91799. this._boundingVectors.push(maxPoint.clone());
  91800. this._boundingVectors[6].x = minPoint.x;
  91801. this._boundingVectors.push(maxPoint.clone());
  91802. this._boundingVectors[7].y = minPoint.y;
  91803. }
  91804. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91805. // Property
  91806. get: function () {
  91807. return this._capacity;
  91808. },
  91809. enumerable: true,
  91810. configurable: true
  91811. });
  91812. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91813. get: function () {
  91814. return this._minPoint;
  91815. },
  91816. enumerable: true,
  91817. configurable: true
  91818. });
  91819. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91820. get: function () {
  91821. return this._maxPoint;
  91822. },
  91823. enumerable: true,
  91824. configurable: true
  91825. });
  91826. // Methods
  91827. OctreeBlock.prototype.addEntry = function (entry) {
  91828. if (this.blocks) {
  91829. for (var index = 0; index < this.blocks.length; index++) {
  91830. var block = this.blocks[index];
  91831. block.addEntry(entry);
  91832. }
  91833. return;
  91834. }
  91835. this._creationFunc(entry, this);
  91836. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91837. this.createInnerBlocks();
  91838. }
  91839. };
  91840. OctreeBlock.prototype.addEntries = function (entries) {
  91841. for (var index = 0; index < entries.length; index++) {
  91842. var mesh = entries[index];
  91843. this.addEntry(mesh);
  91844. }
  91845. };
  91846. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91847. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91848. if (this.blocks) {
  91849. for (var index = 0; index < this.blocks.length; index++) {
  91850. var block = this.blocks[index];
  91851. block.select(frustumPlanes, selection, allowDuplicate);
  91852. }
  91853. return;
  91854. }
  91855. if (allowDuplicate) {
  91856. selection.concat(this.entries);
  91857. }
  91858. else {
  91859. selection.concatWithNoDuplicate(this.entries);
  91860. }
  91861. }
  91862. };
  91863. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91864. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91865. if (this.blocks) {
  91866. for (var index = 0; index < this.blocks.length; index++) {
  91867. var block = this.blocks[index];
  91868. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91869. }
  91870. return;
  91871. }
  91872. if (allowDuplicate) {
  91873. selection.concat(this.entries);
  91874. }
  91875. else {
  91876. selection.concatWithNoDuplicate(this.entries);
  91877. }
  91878. }
  91879. };
  91880. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91881. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91882. if (this.blocks) {
  91883. for (var index = 0; index < this.blocks.length; index++) {
  91884. var block = this.blocks[index];
  91885. block.intersectsRay(ray, selection);
  91886. }
  91887. return;
  91888. }
  91889. selection.concatWithNoDuplicate(this.entries);
  91890. }
  91891. };
  91892. OctreeBlock.prototype.createInnerBlocks = function () {
  91893. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91894. };
  91895. return OctreeBlock;
  91896. }());
  91897. BABYLON.OctreeBlock = OctreeBlock;
  91898. })(BABYLON || (BABYLON = {}));
  91899. //# sourceMappingURL=babylon.octreeBlock.js.map
  91900. var BABYLON;
  91901. (function (BABYLON) {
  91902. /**
  91903. * Postprocess used to generate anaglyphic rendering
  91904. */
  91905. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91906. __extends(AnaglyphPostProcess, _super);
  91907. /**
  91908. * Creates a new AnaglyphPostProcess
  91909. * @param name defines postprocess name
  91910. * @param options defines creation options or target ratio scale
  91911. * @param rigCameras defines cameras using this postprocess
  91912. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91913. * @param engine defines hosting engine
  91914. * @param reusable defines if the postprocess will be reused multiple times per frame
  91915. */
  91916. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91917. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91918. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91919. _this.onApplyObservable.add(function (effect) {
  91920. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91921. });
  91922. return _this;
  91923. }
  91924. return AnaglyphPostProcess;
  91925. }(BABYLON.PostProcess));
  91926. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91927. })(BABYLON || (BABYLON = {}));
  91928. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91929. var BABYLON;
  91930. (function (BABYLON) {
  91931. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91932. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91933. });
  91934. /**
  91935. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91936. */
  91937. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91938. __extends(AnaglyphArcRotateCamera, _super);
  91939. /**
  91940. * Creates a new AnaglyphArcRotateCamera
  91941. * @param name defines camera name
  91942. * @param alpha defines alpha angle (in radians)
  91943. * @param beta defines beta angle (in radians)
  91944. * @param radius defines radius
  91945. * @param target defines camera target
  91946. * @param interaxialDistance defines distance between each color axis
  91947. * @param scene defines the hosting scene
  91948. */
  91949. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91950. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91951. _this.interaxialDistance = interaxialDistance;
  91952. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91953. return _this;
  91954. }
  91955. /**
  91956. * Gets camera class name
  91957. * @returns AnaglyphArcRotateCamera
  91958. */
  91959. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91960. return "AnaglyphArcRotateCamera";
  91961. };
  91962. return AnaglyphArcRotateCamera;
  91963. }(BABYLON.ArcRotateCamera));
  91964. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91965. })(BABYLON || (BABYLON = {}));
  91966. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  91967. var BABYLON;
  91968. (function (BABYLON) {
  91969. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  91970. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91971. });
  91972. /**
  91973. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91974. */
  91975. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91976. __extends(AnaglyphFreeCamera, _super);
  91977. /**
  91978. * Creates a new AnaglyphFreeCamera
  91979. * @param name defines camera name
  91980. * @param position defines initial position
  91981. * @param interaxialDistance defines distance between each color axis
  91982. * @param scene defines the hosting scene
  91983. */
  91984. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91985. var _this = _super.call(this, name, position, scene) || this;
  91986. _this.interaxialDistance = interaxialDistance;
  91987. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91988. return _this;
  91989. }
  91990. /**
  91991. * Gets camera class name
  91992. * @returns AnaglyphFreeCamera
  91993. */
  91994. AnaglyphFreeCamera.prototype.getClassName = function () {
  91995. return "AnaglyphFreeCamera";
  91996. };
  91997. return AnaglyphFreeCamera;
  91998. }(BABYLON.FreeCamera));
  91999. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  92000. })(BABYLON || (BABYLON = {}));
  92001. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  92002. var BABYLON;
  92003. (function (BABYLON) {
  92004. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  92005. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92006. });
  92007. /**
  92008. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  92009. */
  92010. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  92011. __extends(AnaglyphGamepadCamera, _super);
  92012. /**
  92013. * Creates a new AnaglyphGamepadCamera
  92014. * @param name defines camera name
  92015. * @param position defines initial position
  92016. * @param interaxialDistance defines distance between each color axis
  92017. * @param scene defines the hosting scene
  92018. */
  92019. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  92020. var _this = _super.call(this, name, position, scene) || this;
  92021. _this.interaxialDistance = interaxialDistance;
  92022. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92023. return _this;
  92024. }
  92025. /**
  92026. * Gets camera class name
  92027. * @returns AnaglyphGamepadCamera
  92028. */
  92029. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92030. return "AnaglyphGamepadCamera";
  92031. };
  92032. return AnaglyphGamepadCamera;
  92033. }(BABYLON.GamepadCamera));
  92034. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92035. })(BABYLON || (BABYLON = {}));
  92036. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  92037. var BABYLON;
  92038. (function (BABYLON) {
  92039. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  92040. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92041. });
  92042. /**
  92043. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92044. */
  92045. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92046. __extends(AnaglyphUniversalCamera, _super);
  92047. /**
  92048. * Creates a new AnaglyphUniversalCamera
  92049. * @param name defines camera name
  92050. * @param position defines initial position
  92051. * @param interaxialDistance defines distance between each color axis
  92052. * @param scene defines the hosting scene
  92053. */
  92054. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92055. var _this = _super.call(this, name, position, scene) || this;
  92056. _this.interaxialDistance = interaxialDistance;
  92057. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92058. return _this;
  92059. }
  92060. /**
  92061. * Gets camera class name
  92062. * @returns AnaglyphUniversalCamera
  92063. */
  92064. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92065. return "AnaglyphUniversalCamera";
  92066. };
  92067. return AnaglyphUniversalCamera;
  92068. }(BABYLON.UniversalCamera));
  92069. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92070. })(BABYLON || (BABYLON = {}));
  92071. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  92072. var BABYLON;
  92073. (function (BABYLON) {
  92074. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  92075. __extends(StereoscopicInterlacePostProcess, _super);
  92076. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  92077. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  92078. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92079. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92080. _this.onSizeChangedObservable.add(function () {
  92081. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92082. });
  92083. _this.onApplyObservable.add(function (effect) {
  92084. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  92085. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  92086. });
  92087. return _this;
  92088. }
  92089. return StereoscopicInterlacePostProcess;
  92090. }(BABYLON.PostProcess));
  92091. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  92092. })(BABYLON || (BABYLON = {}));
  92093. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  92094. var BABYLON;
  92095. (function (BABYLON) {
  92096. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  92097. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92098. });
  92099. /**
  92100. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92101. */
  92102. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92103. __extends(StereoscopicArcRotateCamera, _super);
  92104. /**
  92105. * Creates a new StereoscopicArcRotateCamera
  92106. * @param name defines camera name
  92107. * @param alpha defines alpha angle (in radians)
  92108. * @param beta defines beta angle (in radians)
  92109. * @param radius defines radius
  92110. * @param target defines camera target
  92111. * @param interaxialDistance defines distance between each color axis
  92112. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92113. * @param scene defines the hosting scene
  92114. */
  92115. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92116. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92117. _this.interaxialDistance = interaxialDistance;
  92118. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92119. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92120. return _this;
  92121. }
  92122. /**
  92123. * Gets camera class name
  92124. * @returns StereoscopicArcRotateCamera
  92125. */
  92126. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92127. return "StereoscopicArcRotateCamera";
  92128. };
  92129. return StereoscopicArcRotateCamera;
  92130. }(BABYLON.ArcRotateCamera));
  92131. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92132. })(BABYLON || (BABYLON = {}));
  92133. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  92134. var BABYLON;
  92135. (function (BABYLON) {
  92136. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92137. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92138. });
  92139. /**
  92140. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92141. */
  92142. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92143. __extends(StereoscopicFreeCamera, _super);
  92144. /**
  92145. * Creates a new StereoscopicFreeCamera
  92146. * @param name defines camera name
  92147. * @param position defines initial position
  92148. * @param interaxialDistance defines distance between each color axis
  92149. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92150. * @param scene defines the hosting scene
  92151. */
  92152. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92153. var _this = _super.call(this, name, position, scene) || this;
  92154. _this.interaxialDistance = interaxialDistance;
  92155. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92156. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92157. return _this;
  92158. }
  92159. /**
  92160. * Gets camera class name
  92161. * @returns StereoscopicFreeCamera
  92162. */
  92163. StereoscopicFreeCamera.prototype.getClassName = function () {
  92164. return "StereoscopicFreeCamera";
  92165. };
  92166. return StereoscopicFreeCamera;
  92167. }(BABYLON.FreeCamera));
  92168. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92169. })(BABYLON || (BABYLON = {}));
  92170. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  92171. var BABYLON;
  92172. (function (BABYLON) {
  92173. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  92174. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92175. });
  92176. /**
  92177. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92178. */
  92179. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92180. __extends(StereoscopicGamepadCamera, _super);
  92181. /**
  92182. * Creates a new StereoscopicGamepadCamera
  92183. * @param name defines camera name
  92184. * @param position defines initial position
  92185. * @param interaxialDistance defines distance between each color axis
  92186. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92187. * @param scene defines the hosting scene
  92188. */
  92189. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92190. var _this = _super.call(this, name, position, scene) || this;
  92191. _this.interaxialDistance = interaxialDistance;
  92192. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92193. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92194. return _this;
  92195. }
  92196. /**
  92197. * Gets camera class name
  92198. * @returns StereoscopicGamepadCamera
  92199. */
  92200. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92201. return "StereoscopicGamepadCamera";
  92202. };
  92203. return StereoscopicGamepadCamera;
  92204. }(BABYLON.GamepadCamera));
  92205. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92206. })(BABYLON || (BABYLON = {}));
  92207. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  92208. var BABYLON;
  92209. (function (BABYLON) {
  92210. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92211. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92212. });
  92213. /**
  92214. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92215. */
  92216. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92217. __extends(StereoscopicUniversalCamera, _super);
  92218. /**
  92219. * Creates a new StereoscopicUniversalCamera
  92220. * @param name defines camera name
  92221. * @param position defines initial position
  92222. * @param interaxialDistance defines distance between each color axis
  92223. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92224. * @param scene defines the hosting scene
  92225. */
  92226. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92227. var _this = _super.call(this, name, position, scene) || this;
  92228. _this.interaxialDistance = interaxialDistance;
  92229. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92230. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92231. return _this;
  92232. }
  92233. /**
  92234. * Gets camera class name
  92235. * @returns StereoscopicUniversalCamera
  92236. */
  92237. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92238. return "StereoscopicUniversalCamera";
  92239. };
  92240. return StereoscopicUniversalCamera;
  92241. }(BABYLON.UniversalCamera));
  92242. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92243. })(BABYLON || (BABYLON = {}));
  92244. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  92245. var BABYLON;
  92246. (function (BABYLON) {
  92247. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  92248. __extends(VRDistortionCorrectionPostProcess, _super);
  92249. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  92250. var _this = _super.call(this, name, "vrDistortionCorrection", [
  92251. 'LensCenter',
  92252. 'Scale',
  92253. 'ScaleIn',
  92254. 'HmdWarpParam'
  92255. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  92256. _this._isRightEye = isRightEye;
  92257. _this._distortionFactors = vrMetrics.distortionK;
  92258. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  92259. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  92260. _this.adaptScaleToCurrentViewport = true;
  92261. _this.onSizeChangedObservable.add(function () {
  92262. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  92263. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  92264. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  92265. });
  92266. _this.onApplyObservable.add(function (effect) {
  92267. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  92268. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  92269. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  92270. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  92271. });
  92272. return _this;
  92273. }
  92274. return VRDistortionCorrectionPostProcess;
  92275. }(BABYLON.PostProcess));
  92276. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  92277. })(BABYLON || (BABYLON = {}));
  92278. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  92279. var BABYLON;
  92280. (function (BABYLON) {
  92281. /**
  92282. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  92283. * Screen rotation is taken into account.
  92284. */
  92285. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  92286. function FreeCameraDeviceOrientationInput() {
  92287. var _this = this;
  92288. this._screenOrientationAngle = 0;
  92289. this._screenQuaternion = new BABYLON.Quaternion();
  92290. this._alpha = 0;
  92291. this._beta = 0;
  92292. this._gamma = 0;
  92293. this._orientationChanged = function () {
  92294. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  92295. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  92296. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  92297. };
  92298. this._deviceOrientation = function (evt) {
  92299. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  92300. _this._beta = evt.beta !== null ? evt.beta : 0;
  92301. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  92302. };
  92303. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  92304. this._orientationChanged();
  92305. }
  92306. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  92307. get: function () {
  92308. return this._camera;
  92309. },
  92310. set: function (camera) {
  92311. this._camera = camera;
  92312. if (this._camera != null && !this._camera.rotationQuaternion) {
  92313. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  92314. }
  92315. },
  92316. enumerable: true,
  92317. configurable: true
  92318. });
  92319. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92320. window.addEventListener("orientationchange", this._orientationChanged);
  92321. window.addEventListener("deviceorientation", this._deviceOrientation);
  92322. //In certain cases, the attach control is called AFTER orientation was changed,
  92323. //So this is needed.
  92324. this._orientationChanged();
  92325. };
  92326. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  92327. window.removeEventListener("orientationchange", this._orientationChanged);
  92328. window.removeEventListener("deviceorientation", this._deviceOrientation);
  92329. };
  92330. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  92331. //if no device orientation provided, don't update the rotation.
  92332. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  92333. if (!this._alpha)
  92334. return;
  92335. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  92336. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  92337. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  92338. //Mirror on XY Plane
  92339. this._camera.rotationQuaternion.z *= -1;
  92340. this._camera.rotationQuaternion.w *= -1;
  92341. };
  92342. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  92343. return "FreeCameraDeviceOrientationInput";
  92344. };
  92345. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  92346. return "deviceOrientation";
  92347. };
  92348. return FreeCameraDeviceOrientationInput;
  92349. }());
  92350. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  92351. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  92352. })(BABYLON || (BABYLON = {}));
  92353. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  92354. var BABYLON;
  92355. (function (BABYLON) {
  92356. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  92357. function ArcRotateCameraVRDeviceOrientationInput() {
  92358. this.alphaCorrection = 1;
  92359. this.betaCorrection = 1;
  92360. this.gammaCorrection = 1;
  92361. this._alpha = 0;
  92362. this._gamma = 0;
  92363. this._dirty = false;
  92364. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  92365. }
  92366. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92367. this.camera.attachControl(element, noPreventDefault);
  92368. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  92369. };
  92370. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  92371. if (evt.alpha !== null) {
  92372. this._alpha = +evt.alpha | 0;
  92373. }
  92374. if (evt.gamma !== null) {
  92375. this._gamma = +evt.gamma | 0;
  92376. }
  92377. this._dirty = true;
  92378. };
  92379. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  92380. if (this._dirty) {
  92381. this._dirty = false;
  92382. if (this._gamma < 0) {
  92383. this._gamma = 180 + this._gamma;
  92384. }
  92385. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  92386. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  92387. }
  92388. };
  92389. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  92390. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  92391. };
  92392. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  92393. return "ArcRotateCameraVRDeviceOrientationInput";
  92394. };
  92395. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  92396. return "VRDeviceOrientation";
  92397. };
  92398. return ArcRotateCameraVRDeviceOrientationInput;
  92399. }());
  92400. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  92401. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  92402. })(BABYLON || (BABYLON = {}));
  92403. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  92404. var BABYLON;
  92405. (function (BABYLON) {
  92406. var VRCameraMetrics = /** @class */ (function () {
  92407. function VRCameraMetrics() {
  92408. this.compensateDistortion = true;
  92409. }
  92410. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  92411. get: function () {
  92412. return this.hResolution / (2 * this.vResolution);
  92413. },
  92414. enumerable: true,
  92415. configurable: true
  92416. });
  92417. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  92418. get: function () {
  92419. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  92420. },
  92421. enumerable: true,
  92422. configurable: true
  92423. });
  92424. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  92425. get: function () {
  92426. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92427. var h = (4 * meters) / this.hScreenSize;
  92428. return BABYLON.Matrix.Translation(h, 0, 0);
  92429. },
  92430. enumerable: true,
  92431. configurable: true
  92432. });
  92433. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  92434. get: function () {
  92435. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92436. var h = (4 * meters) / this.hScreenSize;
  92437. return BABYLON.Matrix.Translation(-h, 0, 0);
  92438. },
  92439. enumerable: true,
  92440. configurable: true
  92441. });
  92442. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  92443. get: function () {
  92444. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  92445. },
  92446. enumerable: true,
  92447. configurable: true
  92448. });
  92449. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  92450. get: function () {
  92451. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  92452. },
  92453. enumerable: true,
  92454. configurable: true
  92455. });
  92456. VRCameraMetrics.GetDefault = function () {
  92457. var result = new VRCameraMetrics();
  92458. result.hResolution = 1280;
  92459. result.vResolution = 800;
  92460. result.hScreenSize = 0.149759993;
  92461. result.vScreenSize = 0.0935999975;
  92462. result.vScreenCenter = 0.0467999987;
  92463. result.eyeToScreenDistance = 0.0410000011;
  92464. result.lensSeparationDistance = 0.0635000020;
  92465. result.interpupillaryDistance = 0.0640000030;
  92466. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  92467. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  92468. result.postProcessScaleFactor = 1.714605507808412;
  92469. result.lensCenterOffset = 0.151976421;
  92470. return result;
  92471. };
  92472. return VRCameraMetrics;
  92473. }());
  92474. BABYLON.VRCameraMetrics = VRCameraMetrics;
  92475. })(BABYLON || (BABYLON = {}));
  92476. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  92477. var BABYLON;
  92478. (function (BABYLON) {
  92479. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  92480. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92481. });
  92482. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  92483. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92484. });
  92485. /**
  92486. * This represents a WebVR camera.
  92487. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  92488. * @example http://doc.babylonjs.com/how_to/webvr_camera
  92489. */
  92490. var WebVRFreeCamera = /** @class */ (function (_super) {
  92491. __extends(WebVRFreeCamera, _super);
  92492. /**
  92493. * Instantiates a WebVRFreeCamera.
  92494. * @param name The name of the WebVRFreeCamera
  92495. * @param position The starting anchor position for the camera
  92496. * @param scene The scene the camera belongs to
  92497. * @param webVROptions a set of customizable options for the webVRCamera
  92498. */
  92499. function WebVRFreeCamera(name, position, scene, webVROptions) {
  92500. if (webVROptions === void 0) { webVROptions = {}; }
  92501. var _this = _super.call(this, name, position, scene) || this;
  92502. _this.webVROptions = webVROptions;
  92503. /**
  92504. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  92505. */
  92506. _this._vrDevice = null;
  92507. /**
  92508. * The rawPose of the vrDevice.
  92509. */
  92510. _this.rawPose = null;
  92511. _this._specsVersion = "1.1";
  92512. _this._attached = false;
  92513. _this._descendants = [];
  92514. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  92515. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  92516. /** @hidden */
  92517. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  92518. _this._standingMatrix = null;
  92519. /**
  92520. * Represents device position in babylon space.
  92521. */
  92522. _this.devicePosition = BABYLON.Vector3.Zero();
  92523. /**
  92524. * Represents device rotation in babylon space.
  92525. */
  92526. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  92527. /**
  92528. * The scale of the device to be used when translating from device space to babylon space.
  92529. */
  92530. _this.deviceScaleFactor = 1;
  92531. _this._deviceToWorld = BABYLON.Matrix.Identity();
  92532. _this._worldToDevice = BABYLON.Matrix.Identity();
  92533. /**
  92534. * References to the webVR controllers for the vrDevice.
  92535. */
  92536. _this.controllers = [];
  92537. /**
  92538. * Emits an event when a controller is attached.
  92539. */
  92540. _this.onControllersAttachedObservable = new BABYLON.Observable();
  92541. /**
  92542. * Emits an event when a controller's mesh has been loaded;
  92543. */
  92544. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92545. /**
  92546. * Emits an event when the HMD's pose has been updated.
  92547. */
  92548. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  92549. _this._poseSet = false;
  92550. /**
  92551. * If the rig cameras be used as parent instead of this camera.
  92552. */
  92553. _this.rigParenting = true;
  92554. _this._defaultHeight = undefined;
  92555. _this._workingVector = BABYLON.Vector3.Zero();
  92556. _this._oneVector = BABYLON.Vector3.One();
  92557. _this._workingMatrix = BABYLON.Matrix.Identity();
  92558. _this._cache.position = BABYLON.Vector3.Zero();
  92559. if (webVROptions.defaultHeight) {
  92560. _this._defaultHeight = webVROptions.defaultHeight;
  92561. _this.position.y = _this._defaultHeight;
  92562. }
  92563. _this.minZ = 0.1;
  92564. //legacy support - the compensation boolean was removed.
  92565. if (arguments.length === 5) {
  92566. _this.webVROptions = arguments[4];
  92567. }
  92568. // default webVR options
  92569. if (_this.webVROptions.trackPosition == undefined) {
  92570. _this.webVROptions.trackPosition = true;
  92571. }
  92572. if (_this.webVROptions.controllerMeshes == undefined) {
  92573. _this.webVROptions.controllerMeshes = true;
  92574. }
  92575. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  92576. _this.webVROptions.defaultLightingOnControllers = true;
  92577. }
  92578. _this.rotationQuaternion = new BABYLON.Quaternion();
  92579. if (_this.webVROptions && _this.webVROptions.positionScale) {
  92580. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  92581. }
  92582. //enable VR
  92583. var engine = _this.getEngine();
  92584. _this._onVREnabled = function (success) { if (success) {
  92585. _this.initControllers();
  92586. } };
  92587. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  92588. engine.initWebVR().add(function (event) {
  92589. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  92590. return;
  92591. }
  92592. _this._vrDevice = event.vrDisplay;
  92593. //reset the rig parameters.
  92594. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  92595. if (_this._attached) {
  92596. _this.getEngine().enableVR();
  92597. }
  92598. });
  92599. if (typeof (VRFrameData) !== "undefined")
  92600. _this._frameData = new VRFrameData();
  92601. /**
  92602. * The idea behind the following lines:
  92603. * objects that have the camera as parent should actually have the rig cameras as a parent.
  92604. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  92605. * the second will not show it correctly.
  92606. *
  92607. * To solve this - each object that has the camera as parent will be added to a protected array.
  92608. * When the rig camera renders, it will take this array and set all of those to be its children.
  92609. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  92610. * Amazing!
  92611. */
  92612. scene.onBeforeCameraRenderObservable.add(function (camera) {
  92613. if (camera.parent === _this && _this.rigParenting) {
  92614. _this._descendants = _this.getDescendants(true, function (n) {
  92615. // don't take the cameras or the controllers!
  92616. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  92617. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  92618. return !isController && !isRigCamera;
  92619. });
  92620. _this._descendants.forEach(function (node) {
  92621. node.parent = camera;
  92622. });
  92623. }
  92624. });
  92625. scene.onAfterCameraRenderObservable.add(function (camera) {
  92626. if (camera.parent === _this && _this.rigParenting) {
  92627. _this._descendants.forEach(function (node) {
  92628. node.parent = _this;
  92629. });
  92630. }
  92631. });
  92632. return _this;
  92633. }
  92634. /**
  92635. * Gets the device distance from the ground in meters.
  92636. * @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.
  92637. */
  92638. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  92639. if (this._standingMatrix) {
  92640. // Add standing matrix offset to get real offset from ground in room
  92641. this._standingMatrix.getTranslationToRef(this._workingVector);
  92642. return this._deviceRoomPosition.y + this._workingVector.y;
  92643. }
  92644. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  92645. return this._defaultHeight || 0;
  92646. };
  92647. /**
  92648. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92649. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  92650. */
  92651. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  92652. var _this = this;
  92653. if (callback === void 0) { callback = function (bool) { }; }
  92654. // Use standing matrix if available
  92655. this.getEngine().initWebVRAsync().then(function (result) {
  92656. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  92657. callback(false);
  92658. }
  92659. else {
  92660. _this._standingMatrix = new BABYLON.Matrix();
  92661. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  92662. if (!_this.getScene().useRightHandedSystem) {
  92663. [2, 6, 8, 9, 14].forEach(function (num) {
  92664. if (_this._standingMatrix) {
  92665. _this._standingMatrix.m[num] *= -1;
  92666. }
  92667. });
  92668. }
  92669. callback(true);
  92670. }
  92671. });
  92672. };
  92673. /**
  92674. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92675. * @returns A promise with a boolean set to if the standing matrix is supported.
  92676. */
  92677. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  92678. var _this = this;
  92679. return new Promise(function (res, rej) {
  92680. _this.useStandingMatrix(function (supported) {
  92681. res(supported);
  92682. });
  92683. });
  92684. };
  92685. /**
  92686. * Disposes the camera
  92687. */
  92688. WebVRFreeCamera.prototype.dispose = function () {
  92689. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  92690. _super.prototype.dispose.call(this);
  92691. };
  92692. /**
  92693. * Gets a vrController by name.
  92694. * @param name The name of the controller to retreive
  92695. * @returns the controller matching the name specified or null if not found
  92696. */
  92697. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  92698. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  92699. var gp = _a[_i];
  92700. if (gp.hand === name) {
  92701. return gp;
  92702. }
  92703. }
  92704. return null;
  92705. };
  92706. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  92707. /**
  92708. * The controller corrisponding to the users left hand.
  92709. */
  92710. get: function () {
  92711. if (!this._leftController) {
  92712. this._leftController = this.getControllerByName("left");
  92713. }
  92714. return this._leftController;
  92715. },
  92716. enumerable: true,
  92717. configurable: true
  92718. });
  92719. ;
  92720. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  92721. /**
  92722. * The controller corrisponding to the users right hand.
  92723. */
  92724. get: function () {
  92725. if (!this._rightController) {
  92726. this._rightController = this.getControllerByName("right");
  92727. }
  92728. return this._rightController;
  92729. },
  92730. enumerable: true,
  92731. configurable: true
  92732. });
  92733. ;
  92734. /**
  92735. * Casts a ray forward from the vrCamera's gaze.
  92736. * @param length Length of the ray (default: 100)
  92737. * @returns the ray corrisponding to the gaze
  92738. */
  92739. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  92740. if (length === void 0) { length = 100; }
  92741. if (this.leftCamera) {
  92742. // Use left eye to avoid computation to compute center on every call
  92743. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  92744. }
  92745. else {
  92746. return _super.prototype.getForwardRay.call(this, length);
  92747. }
  92748. };
  92749. /**
  92750. * Updates the camera based on device's frame data
  92751. */
  92752. WebVRFreeCamera.prototype._checkInputs = function () {
  92753. if (this._vrDevice && this._vrDevice.isPresenting) {
  92754. this._vrDevice.getFrameData(this._frameData);
  92755. this.updateFromDevice(this._frameData.pose);
  92756. }
  92757. _super.prototype._checkInputs.call(this);
  92758. };
  92759. /**
  92760. * Updates the poseControlled values based on the input device pose.
  92761. * @param poseData Pose coming from the device
  92762. */
  92763. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  92764. if (poseData && poseData.orientation) {
  92765. this.rawPose = poseData;
  92766. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  92767. if (this.getScene().useRightHandedSystem) {
  92768. this._deviceRoomRotationQuaternion.z *= -1;
  92769. this._deviceRoomRotationQuaternion.w *= -1;
  92770. }
  92771. if (this.webVROptions.trackPosition && this.rawPose.position) {
  92772. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  92773. if (this.getScene().useRightHandedSystem) {
  92774. this._deviceRoomPosition.z *= -1;
  92775. }
  92776. }
  92777. this._poseSet = true;
  92778. }
  92779. };
  92780. /**
  92781. * WebVR's attach control will start broadcasting frames to the device.
  92782. * Note that in certain browsers (chrome for example) this function must be called
  92783. * within a user-interaction callback. Example:
  92784. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  92785. *
  92786. * @param element html element to attach the vrDevice to
  92787. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  92788. */
  92789. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  92790. _super.prototype.attachControl.call(this, element, noPreventDefault);
  92791. this._attached = true;
  92792. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  92793. if (this._vrDevice) {
  92794. this.getEngine().enableVR();
  92795. }
  92796. };
  92797. /**
  92798. * Detaches the camera from the html element and disables VR
  92799. *
  92800. * @param element html element to detach from
  92801. */
  92802. WebVRFreeCamera.prototype.detachControl = function (element) {
  92803. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  92804. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  92805. _super.prototype.detachControl.call(this, element);
  92806. this._attached = false;
  92807. this.getEngine().disableVR();
  92808. };
  92809. /**
  92810. * @returns the name of this class
  92811. */
  92812. WebVRFreeCamera.prototype.getClassName = function () {
  92813. return "WebVRFreeCamera";
  92814. };
  92815. /**
  92816. * Calls resetPose on the vrDisplay
  92817. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  92818. */
  92819. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  92820. //uses the vrDisplay's "resetPose()".
  92821. //pitch and roll won't be affected.
  92822. this._vrDevice.resetPose();
  92823. };
  92824. /**
  92825. * Updates the rig cameras (left and right eye)
  92826. */
  92827. WebVRFreeCamera.prototype._updateRigCameras = function () {
  92828. var camLeft = this._rigCameras[0];
  92829. var camRight = this._rigCameras[1];
  92830. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92831. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92832. camLeft.position.copyFrom(this._deviceRoomPosition);
  92833. camRight.position.copyFrom(this._deviceRoomPosition);
  92834. };
  92835. /**
  92836. * Updates the cached values of the camera
  92837. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  92838. */
  92839. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  92840. var _this = this;
  92841. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  92842. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  92843. if (!this.updateCacheCalled) {
  92844. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  92845. this.updateCacheCalled = true;
  92846. this.update();
  92847. }
  92848. // Set working vector to the device position in room space rotated by the new rotation
  92849. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  92850. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  92851. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92852. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92853. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92854. // Add translation from anchor position
  92855. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92856. this._workingVector.addInPlace(this.position);
  92857. this._workingVector.subtractInPlace(this._cache.position);
  92858. this._deviceToWorld.setTranslation(this._workingVector);
  92859. // Set an inverted matrix to be used when updating the camera
  92860. this._deviceToWorld.invertToRef(this._worldToDevice);
  92861. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92862. this.controllers.forEach(function (controller) {
  92863. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92864. controller.update();
  92865. });
  92866. }
  92867. if (!ignoreParentClass) {
  92868. _super.prototype._updateCache.call(this);
  92869. }
  92870. this.updateCacheCalled = false;
  92871. };
  92872. /**
  92873. * Updates the current device position and rotation in the babylon world
  92874. */
  92875. WebVRFreeCamera.prototype.update = function () {
  92876. // Get current device position in babylon world
  92877. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  92878. // Get current device rotation in babylon world
  92879. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  92880. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  92881. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  92882. if (this._poseSet) {
  92883. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  92884. }
  92885. _super.prototype.update.call(this);
  92886. };
  92887. /**
  92888. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  92889. * @returns an identity matrix
  92890. */
  92891. WebVRFreeCamera.prototype._getViewMatrix = function () {
  92892. return BABYLON.Matrix.Identity();
  92893. };
  92894. /**
  92895. * This function is called by the two RIG cameras.
  92896. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  92897. */
  92898. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  92899. var _this = this;
  92900. // Update the parent camera prior to using a child camera to avoid desynchronization
  92901. var parentCamera = this._cameraRigParams["parentCamera"];
  92902. parentCamera._updateCache();
  92903. //WebVR 1.1
  92904. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  92905. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  92906. if (!this.getScene().useRightHandedSystem) {
  92907. [2, 6, 8, 9, 14].forEach(function (num) {
  92908. _this._webvrViewMatrix.m[num] *= -1;
  92909. });
  92910. }
  92911. // update the camera rotation matrix
  92912. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  92913. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  92914. // Computing target and final matrix
  92915. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  92916. // should the view matrix be updated with scale and position offset?
  92917. if (parentCamera.deviceScaleFactor !== 1) {
  92918. this._webvrViewMatrix.invert();
  92919. // scale the position, if set
  92920. if (parentCamera.deviceScaleFactor) {
  92921. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  92922. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  92923. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  92924. }
  92925. this._webvrViewMatrix.invert();
  92926. }
  92927. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  92928. // Compute global position
  92929. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  92930. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  92931. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  92932. this._workingMatrix.getTranslationToRef(this._globalPosition);
  92933. this._markSyncedWithParent();
  92934. return this._webvrViewMatrix;
  92935. };
  92936. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  92937. var _this = this;
  92938. var parentCamera = this.parent;
  92939. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  92940. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  92941. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  92942. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  92943. //babylon compatible matrix
  92944. if (!this.getScene().useRightHandedSystem) {
  92945. [8, 9, 10, 11].forEach(function (num) {
  92946. _this._projectionMatrix.m[num] *= -1;
  92947. });
  92948. }
  92949. return this._projectionMatrix;
  92950. };
  92951. /**
  92952. * Initializes the controllers and their meshes
  92953. */
  92954. WebVRFreeCamera.prototype.initControllers = function () {
  92955. var _this = this;
  92956. this.controllers = [];
  92957. var manager = this.getScene().gamepadManager;
  92958. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  92959. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92960. var webVrController = gamepad;
  92961. if (webVrController.defaultModel) {
  92962. webVrController.defaultModel.setEnabled(false);
  92963. }
  92964. if (webVrController.hand === "right") {
  92965. _this._rightController = null;
  92966. }
  92967. if (webVrController.hand === "left") {
  92968. _this._leftController = null;
  92969. }
  92970. var controllerIndex = _this.controllers.indexOf(webVrController);
  92971. if (controllerIndex !== -1) {
  92972. _this.controllers.splice(controllerIndex, 1);
  92973. }
  92974. }
  92975. });
  92976. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  92977. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92978. var webVrController_1 = gamepad;
  92979. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  92980. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  92981. if (_this.webVROptions.controllerMeshes) {
  92982. if (webVrController_1.defaultModel) {
  92983. webVrController_1.defaultModel.setEnabled(true);
  92984. }
  92985. else {
  92986. // Load the meshes
  92987. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  92988. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  92989. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  92990. if (_this.webVROptions.defaultLightingOnControllers) {
  92991. if (!_this._lightOnControllers) {
  92992. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  92993. }
  92994. var activateLightOnSubMeshes_1 = function (mesh, light) {
  92995. var children = mesh.getChildren();
  92996. if (children.length !== 0) {
  92997. children.forEach(function (mesh) {
  92998. light.includedOnlyMeshes.push(mesh);
  92999. activateLightOnSubMeshes_1(mesh, light);
  93000. });
  93001. }
  93002. };
  93003. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  93004. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  93005. }
  93006. });
  93007. }
  93008. }
  93009. webVrController_1.attachToPoseControlledCamera(_this);
  93010. // since this is async - sanity check. Is the controller already stored?
  93011. if (_this.controllers.indexOf(webVrController_1) === -1) {
  93012. //add to the controllers array
  93013. _this.controllers.push(webVrController_1);
  93014. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  93015. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  93016. // So we're overriding setting left & right manually to be sure
  93017. var firstViveWandDetected = false;
  93018. for (var i = 0; i < _this.controllers.length; i++) {
  93019. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93020. if (!firstViveWandDetected) {
  93021. firstViveWandDetected = true;
  93022. _this.controllers[i].hand = "left";
  93023. }
  93024. else {
  93025. _this.controllers[i].hand = "right";
  93026. }
  93027. }
  93028. }
  93029. //did we find enough controllers? Great! let the developer know.
  93030. if (_this.controllers.length >= 2) {
  93031. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  93032. }
  93033. }
  93034. }
  93035. });
  93036. };
  93037. return WebVRFreeCamera;
  93038. }(BABYLON.FreeCamera));
  93039. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  93040. })(BABYLON || (BABYLON = {}));
  93041. //# sourceMappingURL=babylon.webVRCamera.js.map
  93042. var BABYLON;
  93043. (function (BABYLON) {
  93044. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  93045. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  93046. });
  93047. // We're mainly based on the logic defined into the FreeCamera code
  93048. /**
  93049. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  93050. * being tilted forward or back and left or right.
  93051. */
  93052. var DeviceOrientationCamera = /** @class */ (function (_super) {
  93053. __extends(DeviceOrientationCamera, _super);
  93054. /**
  93055. * Creates a new device orientation camera
  93056. * @param name The name of the camera
  93057. * @param position The start position camera
  93058. * @param scene The scene the camera belongs to
  93059. */
  93060. function DeviceOrientationCamera(name, position, scene) {
  93061. var _this = _super.call(this, name, position, scene) || this;
  93062. _this._quaternionCache = new BABYLON.Quaternion();
  93063. _this.inputs.addDeviceOrientation();
  93064. return _this;
  93065. }
  93066. /**
  93067. * Gets the current instance class name ("DeviceOrientationCamera").
  93068. * This helps avoiding instanceof at run time.
  93069. * @returns the class name
  93070. */
  93071. DeviceOrientationCamera.prototype.getClassName = function () {
  93072. return "DeviceOrientationCamera";
  93073. };
  93074. /**
  93075. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  93076. */
  93077. DeviceOrientationCamera.prototype._checkInputs = function () {
  93078. _super.prototype._checkInputs.call(this);
  93079. this._quaternionCache.copyFrom(this.rotationQuaternion);
  93080. if (this._initialQuaternion) {
  93081. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93082. }
  93083. };
  93084. /**
  93085. * Reset the camera to its default orientation on the specified axis only.
  93086. * @param axis The axis to reset
  93087. */
  93088. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  93089. var _this = this;
  93090. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  93091. //can only work if this camera has a rotation quaternion already.
  93092. if (!this.rotationQuaternion)
  93093. return;
  93094. if (!this._initialQuaternion) {
  93095. this._initialQuaternion = new BABYLON.Quaternion();
  93096. }
  93097. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  93098. ['x', 'y', 'z'].forEach(function (axisName) {
  93099. if (!axis[axisName]) {
  93100. _this._initialQuaternion[axisName] = 0;
  93101. }
  93102. else {
  93103. _this._initialQuaternion[axisName] *= -1;
  93104. }
  93105. });
  93106. this._initialQuaternion.normalize();
  93107. //force rotation update
  93108. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93109. };
  93110. return DeviceOrientationCamera;
  93111. }(BABYLON.FreeCamera));
  93112. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  93113. })(BABYLON || (BABYLON = {}));
  93114. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  93115. var BABYLON;
  93116. (function (BABYLON) {
  93117. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93118. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93119. });
  93120. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  93121. __extends(VRDeviceOrientationFreeCamera, _super);
  93122. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93123. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93124. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93125. var _this = _super.call(this, name, position, scene) || this;
  93126. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93127. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93128. return _this;
  93129. }
  93130. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  93131. return "VRDeviceOrientationFreeCamera";
  93132. };
  93133. return VRDeviceOrientationFreeCamera;
  93134. }(BABYLON.DeviceOrientationCamera));
  93135. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  93136. })(BABYLON || (BABYLON = {}));
  93137. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  93138. var BABYLON;
  93139. (function (BABYLON) {
  93140. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93141. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  93142. });
  93143. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  93144. __extends(VRDeviceOrientationArcRotateCamera, _super);
  93145. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  93146. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93147. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93148. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93149. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93150. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93151. _this.inputs.addVRDeviceOrientation();
  93152. return _this;
  93153. }
  93154. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  93155. return "VRDeviceOrientationArcRotateCamera";
  93156. };
  93157. return VRDeviceOrientationArcRotateCamera;
  93158. }(BABYLON.ArcRotateCamera));
  93159. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  93160. })(BABYLON || (BABYLON = {}));
  93161. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  93162. var BABYLON;
  93163. (function (BABYLON) {
  93164. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  93165. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  93166. });
  93167. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  93168. __extends(VRDeviceOrientationGamepadCamera, _super);
  93169. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93170. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93171. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93172. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  93173. _this.inputs.addGamepad();
  93174. return _this;
  93175. }
  93176. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  93177. return "VRDeviceOrientationGamepadCamera";
  93178. };
  93179. return VRDeviceOrientationGamepadCamera;
  93180. }(BABYLON.VRDeviceOrientationFreeCamera));
  93181. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  93182. })(BABYLON || (BABYLON = {}));
  93183. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  93184. var BABYLON;
  93185. (function (BABYLON) {
  93186. var VRExperienceHelperGazer = /** @class */ (function () {
  93187. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  93188. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  93189. this.scene = scene;
  93190. this._pointerDownOnMeshAsked = false;
  93191. this._isActionableMesh = false;
  93192. this._teleportationRequestInitiated = false;
  93193. this._teleportationBackRequestInitiated = false;
  93194. this._rotationRightAsked = false;
  93195. this._rotationLeftAsked = false;
  93196. this._dpadPressed = true;
  93197. this._activePointer = false;
  93198. this._id = VRExperienceHelperGazer._idCounter++;
  93199. // Gaze tracker
  93200. if (!gazeTrackerToClone) {
  93201. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  93202. this._gazeTracker.bakeCurrentTransformIntoVertices();
  93203. this._gazeTracker.isPickable = false;
  93204. this._gazeTracker.isVisible = false;
  93205. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  93206. targetMat.specularColor = BABYLON.Color3.Black();
  93207. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93208. targetMat.backFaceCulling = false;
  93209. this._gazeTracker.material = targetMat;
  93210. }
  93211. else {
  93212. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  93213. }
  93214. }
  93215. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  93216. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  93217. };
  93218. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  93219. this._pointerDownOnMeshAsked = true;
  93220. if (this._currentHit) {
  93221. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  93222. }
  93223. };
  93224. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  93225. if (this._currentHit) {
  93226. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  93227. }
  93228. this._pointerDownOnMeshAsked = false;
  93229. };
  93230. VRExperienceHelperGazer.prototype._activatePointer = function () {
  93231. this._activePointer = true;
  93232. };
  93233. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  93234. this._activePointer = false;
  93235. };
  93236. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  93237. if (distance === void 0) { distance = 100; }
  93238. };
  93239. VRExperienceHelperGazer.prototype.dispose = function () {
  93240. this._interactionsEnabled = false;
  93241. this._teleportationEnabled = false;
  93242. if (this._gazeTracker) {
  93243. this._gazeTracker.dispose();
  93244. }
  93245. };
  93246. VRExperienceHelperGazer._idCounter = 0;
  93247. return VRExperienceHelperGazer;
  93248. }());
  93249. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  93250. __extends(VRExperienceHelperControllerGazer, _super);
  93251. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  93252. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  93253. _this.webVRController = webVRController;
  93254. // Laser pointer
  93255. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  93256. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  93257. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93258. laserPointerMaterial.alpha = 0.6;
  93259. _this._laserPointer.material = laserPointerMaterial;
  93260. _this._laserPointer.rotation.x = Math.PI / 2;
  93261. _this._laserPointer.position.z = -0.5;
  93262. _this._laserPointer.isVisible = false;
  93263. _this._laserPointer.isPickable = false;
  93264. if (!webVRController.mesh) {
  93265. // Create an empty mesh that is used prior to loading the high quality model
  93266. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  93267. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  93268. preloadPointerPose.rotation.x = -0.7;
  93269. preloadMesh.addChild(preloadPointerPose);
  93270. webVRController.attachToMesh(preloadMesh);
  93271. }
  93272. _this._setLaserPointerParent(webVRController.mesh);
  93273. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  93274. _this._setLaserPointerParent(mesh);
  93275. });
  93276. return _this;
  93277. }
  93278. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  93279. return this.webVRController.getForwardRay(length);
  93280. };
  93281. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  93282. _super.prototype._activatePointer.call(this);
  93283. this._laserPointer.isVisible = true;
  93284. };
  93285. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  93286. _super.prototype._deactivatePointer.call(this);
  93287. this._laserPointer.isVisible = false;
  93288. };
  93289. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  93290. this._laserPointer.material.emissiveColor = color;
  93291. };
  93292. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  93293. var makeNotPick = function (root) {
  93294. root.isPickable = false;
  93295. root.getChildMeshes().forEach(function (c) {
  93296. makeNotPick(c);
  93297. });
  93298. };
  93299. makeNotPick(mesh);
  93300. var childMeshes = mesh.getChildMeshes();
  93301. this.webVRController._pointingPoseNode = null;
  93302. for (var i = 0; i < childMeshes.length; i++) {
  93303. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  93304. mesh = childMeshes[i];
  93305. this.webVRController._pointingPoseNode = mesh;
  93306. break;
  93307. }
  93308. }
  93309. this._laserPointer.parent = mesh;
  93310. };
  93311. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  93312. if (distance === void 0) { distance = 100; }
  93313. this._laserPointer.scaling.y = distance;
  93314. this._laserPointer.position.z = -distance / 2;
  93315. };
  93316. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  93317. _super.prototype.dispose.call(this);
  93318. this._laserPointer.dispose();
  93319. if (this._meshAttachedObserver) {
  93320. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  93321. }
  93322. };
  93323. return VRExperienceHelperControllerGazer;
  93324. }(VRExperienceHelperGazer));
  93325. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  93326. __extends(VRExperienceHelperCameraGazer, _super);
  93327. function VRExperienceHelperCameraGazer(getCamera, scene) {
  93328. var _this = _super.call(this, scene) || this;
  93329. _this.getCamera = getCamera;
  93330. return _this;
  93331. }
  93332. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  93333. var camera = this.getCamera();
  93334. if (camera) {
  93335. return camera.getForwardRay(length);
  93336. }
  93337. else {
  93338. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  93339. }
  93340. };
  93341. return VRExperienceHelperCameraGazer;
  93342. }(VRExperienceHelperGazer));
  93343. /**
  93344. * Helps to quickly add VR support to an existing scene.
  93345. * See http://doc.babylonjs.com/how_to/webvr_helper
  93346. */
  93347. var VRExperienceHelper = /** @class */ (function () {
  93348. /**
  93349. * Instantiates a VRExperienceHelper.
  93350. * Helps to quickly add VR support to an existing scene.
  93351. * @param scene The scene the VRExperienceHelper belongs to.
  93352. * @param webVROptions Options to modify the vr experience helper's behavior.
  93353. */
  93354. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  93355. if (webVROptions === void 0) { webVROptions = {}; }
  93356. var _this = this;
  93357. this.webVROptions = webVROptions;
  93358. // Can the system support WebVR, even if a headset isn't plugged in?
  93359. this._webVRsupported = false;
  93360. // If WebVR is supported, is a headset plugged in and are we ready to present?
  93361. this._webVRready = false;
  93362. // Are we waiting for the requestPresent callback to complete?
  93363. this._webVRrequesting = false;
  93364. // Are we presenting to the headset right now?
  93365. this._webVRpresenting = false;
  93366. // Are we presenting in the fullscreen fallback?
  93367. this._fullscreenVRpresenting = false;
  93368. /**
  93369. * Observable raised when entering VR.
  93370. */
  93371. this.onEnteringVRObservable = new BABYLON.Observable();
  93372. /**
  93373. * Observable raised when exiting VR.
  93374. */
  93375. this.onExitingVRObservable = new BABYLON.Observable();
  93376. /**
  93377. * Observable raised when controller mesh is loaded.
  93378. */
  93379. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93380. this._useCustomVRButton = false;
  93381. this._teleportationRequested = false;
  93382. this._teleportActive = false;
  93383. this._floorMeshesCollection = [];
  93384. this._rotationAllowed = true;
  93385. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  93386. this._isDefaultTeleportationTarget = true;
  93387. this._teleportationFillColor = "#444444";
  93388. this._teleportationBorderColor = "#FFFFFF";
  93389. this._rotationAngle = 0;
  93390. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  93391. this._padSensibilityUp = 0.65;
  93392. this._padSensibilityDown = 0.35;
  93393. this.leftController = null;
  93394. this.rightController = null;
  93395. /**
  93396. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  93397. */
  93398. this.onNewMeshSelected = new BABYLON.Observable();
  93399. /**
  93400. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  93401. */
  93402. this.onNewMeshPicked = new BABYLON.Observable();
  93403. /**
  93404. * Observable raised before camera teleportation
  93405. */
  93406. this.onBeforeCameraTeleport = new BABYLON.Observable();
  93407. /**
  93408. * Observable raised after camera teleportation
  93409. */
  93410. this.onAfterCameraTeleport = new BABYLON.Observable();
  93411. /**
  93412. * Observable raised when current selected mesh gets unselected
  93413. */
  93414. this.onSelectedMeshUnselected = new BABYLON.Observable();
  93415. /**
  93416. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  93417. */
  93418. this.teleportationEnabled = true;
  93419. this._teleportationInitialized = false;
  93420. this._interactionsEnabled = false;
  93421. this._interactionsRequested = false;
  93422. this._displayGaze = true;
  93423. this._displayLaserPointer = true;
  93424. this._onResize = function () {
  93425. _this.moveButtonToBottomRight();
  93426. if (_this._fullscreenVRpresenting && _this._webVRready) {
  93427. _this.exitVR();
  93428. }
  93429. };
  93430. this._onFullscreenChange = function () {
  93431. if (document.fullscreen !== undefined) {
  93432. _this._fullscreenVRpresenting = document.fullscreen;
  93433. }
  93434. else if (document.mozFullScreen !== undefined) {
  93435. _this._fullscreenVRpresenting = document.mozFullScreen;
  93436. }
  93437. else if (document.webkitIsFullScreen !== undefined) {
  93438. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  93439. }
  93440. else if (document.msIsFullScreen !== undefined) {
  93441. _this._fullscreenVRpresenting = document.msIsFullScreen;
  93442. }
  93443. else if (document.msFullscreenElement !== undefined) {
  93444. _this._fullscreenVRpresenting = document.msFullscreenElement;
  93445. }
  93446. if (!_this._fullscreenVRpresenting && _this._canvas) {
  93447. _this.exitVR();
  93448. if (!_this._useCustomVRButton) {
  93449. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  93450. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  93451. }
  93452. }
  93453. };
  93454. this.beforeRender = function () {
  93455. if (_this.leftController && _this.leftController._activePointer) {
  93456. _this._castRayAndSelectObject(_this.leftController);
  93457. }
  93458. if (_this.rightController && _this.rightController._activePointer) {
  93459. _this._castRayAndSelectObject(_this.rightController);
  93460. }
  93461. if (_this._noControllerIsActive) {
  93462. _this._castRayAndSelectObject(_this._cameraGazer);
  93463. }
  93464. else {
  93465. _this._cameraGazer._gazeTracker.isVisible = false;
  93466. }
  93467. };
  93468. this._onNewGamepadConnected = function (gamepad) {
  93469. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  93470. if (gamepad.leftStick) {
  93471. gamepad.onleftstickchanged(function (stickValues) {
  93472. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  93473. // Listening to classic/xbox gamepad only if no VR controller is active
  93474. if ((!_this.leftController && !_this.rightController) ||
  93475. ((_this.leftController && !_this.leftController._activePointer) &&
  93476. (_this.rightController && !_this.rightController._activePointer))) {
  93477. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  93478. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  93479. }
  93480. }
  93481. });
  93482. }
  93483. if (gamepad.rightStick) {
  93484. gamepad.onrightstickchanged(function (stickValues) {
  93485. if (_this._teleportationInitialized) {
  93486. _this._checkRotate(stickValues, _this._cameraGazer);
  93487. }
  93488. });
  93489. }
  93490. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  93491. gamepad.onbuttondown(function (buttonPressed) {
  93492. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93493. _this._cameraGazer._selectionPointerDown();
  93494. }
  93495. });
  93496. gamepad.onbuttonup(function (buttonPressed) {
  93497. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93498. _this._cameraGazer._selectionPointerUp();
  93499. }
  93500. });
  93501. }
  93502. }
  93503. else {
  93504. var webVRController = gamepad;
  93505. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  93506. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  93507. _this.rightController = controller;
  93508. }
  93509. else {
  93510. _this.leftController = controller;
  93511. }
  93512. _this._tryEnableInteractionOnController(controller);
  93513. }
  93514. };
  93515. // 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
  93516. this._tryEnableInteractionOnController = function (controller) {
  93517. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  93518. _this._enableInteractionOnController(controller);
  93519. }
  93520. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  93521. _this._enableTeleportationOnController(controller);
  93522. }
  93523. };
  93524. this._onNewGamepadDisconnected = function (gamepad) {
  93525. if (gamepad instanceof BABYLON.WebVRController) {
  93526. if (gamepad.hand === "left" && _this.leftController != null) {
  93527. _this.leftController.dispose();
  93528. _this.leftController = null;
  93529. }
  93530. if (gamepad.hand === "right" && _this.rightController != null) {
  93531. _this.rightController.dispose();
  93532. _this.rightController = null;
  93533. }
  93534. }
  93535. };
  93536. this._workingVector = BABYLON.Vector3.Zero();
  93537. this._workingQuaternion = BABYLON.Quaternion.Identity();
  93538. this._workingMatrix = BABYLON.Matrix.Identity();
  93539. this._scene = scene;
  93540. this._canvas = scene.getEngine().getRenderingCanvas();
  93541. // Parse options
  93542. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  93543. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  93544. }
  93545. if (webVROptions.createDeviceOrientationCamera === undefined) {
  93546. webVROptions.createDeviceOrientationCamera = true;
  93547. }
  93548. if (webVROptions.laserToggle === undefined) {
  93549. webVROptions.laserToggle = true;
  93550. }
  93551. if (webVROptions.defaultHeight === undefined) {
  93552. webVROptions.defaultHeight = 1.7;
  93553. }
  93554. if (webVROptions.useCustomVRButton) {
  93555. this._useCustomVRButton = true;
  93556. if (webVROptions.customVRButton) {
  93557. this._btnVR = webVROptions.customVRButton;
  93558. }
  93559. }
  93560. if (webVROptions.rayLength) {
  93561. this._rayLength = webVROptions.rayLength;
  93562. }
  93563. this._defaultHeight = webVROptions.defaultHeight;
  93564. if (webVROptions.positionScale) {
  93565. this._rayLength *= webVROptions.positionScale;
  93566. this._defaultHeight *= webVROptions.positionScale;
  93567. }
  93568. // Set position
  93569. if (this._scene.activeCamera) {
  93570. this._position = this._scene.activeCamera.position.clone();
  93571. }
  93572. else {
  93573. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  93574. }
  93575. // Set non-vr camera
  93576. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  93577. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  93578. // Copy data from existing camera
  93579. if (this._scene.activeCamera) {
  93580. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93581. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  93582. // Set rotation from previous camera
  93583. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  93584. var targetCamera = this._scene.activeCamera;
  93585. if (targetCamera.rotationQuaternion) {
  93586. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  93587. }
  93588. else {
  93589. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  93590. }
  93591. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  93592. }
  93593. }
  93594. this._scene.activeCamera = this._deviceOrientationCamera;
  93595. if (this._canvas) {
  93596. this._scene.activeCamera.attachControl(this._canvas);
  93597. }
  93598. }
  93599. else {
  93600. this._existingCamera = this._scene.activeCamera;
  93601. }
  93602. // Create VR cameras
  93603. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93604. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  93605. }
  93606. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  93607. this._webVRCamera.useStandingMatrix();
  93608. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  93609. // Create default button
  93610. if (!this._useCustomVRButton) {
  93611. this._btnVR = document.createElement("BUTTON");
  93612. this._btnVR.className = "babylonVRicon";
  93613. this._btnVR.id = "babylonVRiconbtn";
  93614. this._btnVR.title = "Click to switch to VR";
  93615. 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) }";
  93616. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  93617. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  93618. // css += ".babylonVRicon.vrdisplaysupported { }";
  93619. // css += ".babylonVRicon.vrdisplayready { }";
  93620. // css += ".babylonVRicon.vrdisplayrequesting { }";
  93621. var style = document.createElement('style');
  93622. style.appendChild(document.createTextNode(css));
  93623. document.getElementsByTagName('head')[0].appendChild(style);
  93624. this.moveButtonToBottomRight();
  93625. }
  93626. // VR button click event
  93627. if (this._btnVR) {
  93628. this._btnVR.addEventListener("click", function () {
  93629. if (!_this.isInVRMode) {
  93630. _this.enterVR();
  93631. }
  93632. else {
  93633. _this.exitVR();
  93634. }
  93635. });
  93636. }
  93637. // Window events
  93638. window.addEventListener("resize", this._onResize);
  93639. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  93640. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  93641. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  93642. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  93643. document.onmsfullscreenchange = this._onFullscreenChange;
  93644. // Display vr button when headset is connected
  93645. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93646. this.displayVRButton();
  93647. }
  93648. else {
  93649. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  93650. if (e.vrDisplay) {
  93651. _this.displayVRButton();
  93652. }
  93653. });
  93654. }
  93655. // Exiting VR mode using 'ESC' key on desktop
  93656. this._onKeyDown = function (event) {
  93657. if (event.keyCode === 27 && _this.isInVRMode) {
  93658. _this.exitVR();
  93659. }
  93660. };
  93661. document.addEventListener("keydown", this._onKeyDown);
  93662. // Exiting VR mode double tapping the touch screen
  93663. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  93664. if (_this.isInVRMode) {
  93665. _this.exitVR();
  93666. if (_this._fullscreenVRpresenting) {
  93667. _this._scene.getEngine().switchFullscreen(true);
  93668. }
  93669. }
  93670. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  93671. // Listen for WebVR display changes
  93672. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  93673. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  93674. this._onVRRequestPresentStart = function () {
  93675. _this._webVRrequesting = true;
  93676. _this.updateButtonVisibility();
  93677. };
  93678. this._onVRRequestPresentComplete = function (success) {
  93679. _this._webVRrequesting = false;
  93680. _this.updateButtonVisibility();
  93681. };
  93682. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  93683. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  93684. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  93685. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93686. scene.onDisposeObservable.add(function () {
  93687. _this.dispose();
  93688. });
  93689. // Gamepad connection events
  93690. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  93691. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  93692. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  93693. this.updateButtonVisibility();
  93694. //create easing functions
  93695. this._circleEase = new BABYLON.CircleEase();
  93696. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93697. if (this.webVROptions.floorMeshes) {
  93698. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  93699. }
  93700. }
  93701. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  93702. /** Return this.onEnteringVRObservable
  93703. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  93704. */
  93705. get: function () {
  93706. return this.onEnteringVRObservable;
  93707. },
  93708. enumerable: true,
  93709. configurable: true
  93710. });
  93711. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  93712. /** Return this.onExitingVRObservable
  93713. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  93714. */
  93715. get: function () {
  93716. return this.onExitingVRObservable;
  93717. },
  93718. enumerable: true,
  93719. configurable: true
  93720. });
  93721. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  93722. /** Return this.onControllerMeshLoadedObservable
  93723. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  93724. */
  93725. get: function () {
  93726. return this.onControllerMeshLoadedObservable;
  93727. },
  93728. enumerable: true,
  93729. configurable: true
  93730. });
  93731. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  93732. /**
  93733. * The mesh used to display where the user is going to teleport.
  93734. */
  93735. get: function () {
  93736. return this._teleportationTarget;
  93737. },
  93738. /**
  93739. * Sets the mesh to be used to display where the user is going to teleport.
  93740. */
  93741. set: function (value) {
  93742. if (value) {
  93743. value.name = "teleportationTarget";
  93744. this._isDefaultTeleportationTarget = false;
  93745. this._teleportationTarget = value;
  93746. }
  93747. },
  93748. enumerable: true,
  93749. configurable: true
  93750. });
  93751. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  93752. /**
  93753. * The mesh used to display where the user is selecting,
  93754. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  93755. * See http://doc.babylonjs.com/resources/baking_transformations
  93756. */
  93757. get: function () {
  93758. return this._cameraGazer._gazeTracker;
  93759. },
  93760. set: function (value) {
  93761. if (value) {
  93762. this._cameraGazer._gazeTracker = value;
  93763. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  93764. this._cameraGazer._gazeTracker.isPickable = false;
  93765. this._cameraGazer._gazeTracker.isVisible = false;
  93766. this._cameraGazer._gazeTracker.name = "gazeTracker";
  93767. if (this.leftController) {
  93768. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93769. }
  93770. if (this.rightController) {
  93771. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93772. }
  93773. }
  93774. },
  93775. enumerable: true,
  93776. configurable: true
  93777. });
  93778. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  93779. /**
  93780. * If the ray of the gaze should be displayed.
  93781. */
  93782. get: function () {
  93783. return this._displayGaze;
  93784. },
  93785. /**
  93786. * Sets if the ray of the gaze should be displayed.
  93787. */
  93788. set: function (value) {
  93789. this._displayGaze = value;
  93790. if (!value) {
  93791. this._cameraGazer._gazeTracker.isVisible = false;
  93792. if (this.leftController) {
  93793. this.leftController._gazeTracker.isVisible = false;
  93794. }
  93795. if (this.rightController) {
  93796. this.rightController._gazeTracker.isVisible = false;
  93797. }
  93798. }
  93799. },
  93800. enumerable: true,
  93801. configurable: true
  93802. });
  93803. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  93804. /**
  93805. * If the ray of the LaserPointer should be displayed.
  93806. */
  93807. get: function () {
  93808. return this._displayLaserPointer;
  93809. },
  93810. /**
  93811. * Sets if the ray of the LaserPointer should be displayed.
  93812. */
  93813. set: function (value) {
  93814. this._displayLaserPointer = value;
  93815. if (!value) {
  93816. if (this.rightController) {
  93817. this.rightController._deactivatePointer();
  93818. this.rightController._gazeTracker.isVisible = false;
  93819. }
  93820. if (this.leftController) {
  93821. this.leftController._deactivatePointer();
  93822. this.leftController._gazeTracker.isVisible = false;
  93823. }
  93824. }
  93825. else {
  93826. if (this.rightController) {
  93827. this.rightController._activatePointer();
  93828. }
  93829. if (this.leftController) {
  93830. this.leftController._activatePointer();
  93831. }
  93832. }
  93833. },
  93834. enumerable: true,
  93835. configurable: true
  93836. });
  93837. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93838. /**
  93839. * The deviceOrientationCamera used as the camera when not in VR.
  93840. */
  93841. get: function () {
  93842. return this._deviceOrientationCamera;
  93843. },
  93844. enumerable: true,
  93845. configurable: true
  93846. });
  93847. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93848. /**
  93849. * Based on the current WebVR support, returns the current VR camera used.
  93850. */
  93851. get: function () {
  93852. if (this._webVRready) {
  93853. return this._webVRCamera;
  93854. }
  93855. else {
  93856. return this._scene.activeCamera;
  93857. }
  93858. },
  93859. enumerable: true,
  93860. configurable: true
  93861. });
  93862. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93863. /**
  93864. * The webVRCamera which is used when in VR.
  93865. */
  93866. get: function () {
  93867. return this._webVRCamera;
  93868. },
  93869. enumerable: true,
  93870. configurable: true
  93871. });
  93872. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93873. /**
  93874. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93875. */
  93876. get: function () {
  93877. return this._vrDeviceOrientationCamera;
  93878. },
  93879. enumerable: true,
  93880. configurable: true
  93881. });
  93882. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93883. get: function () {
  93884. var result = this._cameraGazer._teleportationRequestInitiated
  93885. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93886. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93887. return result;
  93888. },
  93889. enumerable: true,
  93890. configurable: true
  93891. });
  93892. // Raised when one of the controller has loaded successfully its associated default mesh
  93893. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93894. if (this.leftController && this.leftController.webVRController == webVRController) {
  93895. if (webVRController.mesh) {
  93896. this.leftController._setLaserPointerParent(webVRController.mesh);
  93897. }
  93898. }
  93899. if (this.rightController && this.rightController.webVRController == webVRController) {
  93900. if (webVRController.mesh) {
  93901. this.rightController._setLaserPointerParent(webVRController.mesh);
  93902. }
  93903. }
  93904. try {
  93905. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93906. }
  93907. catch (err) {
  93908. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93909. }
  93910. };
  93911. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93912. /**
  93913. * Gets a value indicating if we are currently in VR mode.
  93914. */
  93915. get: function () {
  93916. return this._webVRpresenting || this._fullscreenVRpresenting;
  93917. },
  93918. enumerable: true,
  93919. configurable: true
  93920. });
  93921. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93922. var vrDisplay = this._scene.getEngine().getVRDevice();
  93923. if (vrDisplay) {
  93924. var wasPresenting = this._webVRpresenting;
  93925. // A VR display is connected
  93926. this._webVRpresenting = vrDisplay.isPresenting;
  93927. if (wasPresenting && !this._webVRpresenting)
  93928. this.exitVR();
  93929. }
  93930. else {
  93931. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93932. }
  93933. this.updateButtonVisibility();
  93934. };
  93935. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93936. this._webVRsupported = eventArgs.vrSupported;
  93937. this._webVRready = !!eventArgs.vrDisplay;
  93938. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93939. this.updateButtonVisibility();
  93940. };
  93941. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93942. if (this._canvas && !this._useCustomVRButton) {
  93943. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93944. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93945. }
  93946. };
  93947. VRExperienceHelper.prototype.displayVRButton = function () {
  93948. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93949. document.body.appendChild(this._btnVR);
  93950. this._btnVRDisplayed = true;
  93951. }
  93952. };
  93953. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93954. if (!this._btnVR || this._useCustomVRButton) {
  93955. return;
  93956. }
  93957. this._btnVR.className = "babylonVRicon";
  93958. if (this.isInVRMode) {
  93959. this._btnVR.className += " vrdisplaypresenting";
  93960. }
  93961. else {
  93962. if (this._webVRready)
  93963. this._btnVR.className += " vrdisplayready";
  93964. if (this._webVRsupported)
  93965. this._btnVR.className += " vrdisplaysupported";
  93966. if (this._webVRrequesting)
  93967. this._btnVR.className += " vrdisplayrequesting";
  93968. }
  93969. };
  93970. /**
  93971. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93972. * Otherwise, will use the fullscreen API.
  93973. */
  93974. VRExperienceHelper.prototype.enterVR = function () {
  93975. if (this.onEnteringVRObservable) {
  93976. try {
  93977. this.onEnteringVRObservable.notifyObservers(this);
  93978. }
  93979. catch (err) {
  93980. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93981. }
  93982. }
  93983. if (this._scene.activeCamera) {
  93984. this._position = this._scene.activeCamera.position.clone();
  93985. // make sure that we return to the last active camera
  93986. this._existingCamera = this._scene.activeCamera;
  93987. }
  93988. if (this._webVRrequesting)
  93989. return;
  93990. // If WebVR is supported and a headset is connected
  93991. if (this._webVRready) {
  93992. if (!this._webVRpresenting) {
  93993. this._webVRCamera.position = this._position;
  93994. this._scene.activeCamera = this._webVRCamera;
  93995. }
  93996. }
  93997. else if (this._vrDeviceOrientationCamera) {
  93998. this._vrDeviceOrientationCamera.position = this._position;
  93999. if (this._scene.activeCamera) {
  94000. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94001. }
  94002. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  94003. this._scene.getEngine().switchFullscreen(true);
  94004. this.updateButtonVisibility();
  94005. }
  94006. if (this._scene.activeCamera && this._canvas) {
  94007. this._scene.activeCamera.attachControl(this._canvas);
  94008. }
  94009. if (this._interactionsEnabled) {
  94010. this._scene.registerBeforeRender(this.beforeRender);
  94011. }
  94012. };
  94013. /**
  94014. * Attempt to exit VR, or fullscreen.
  94015. */
  94016. VRExperienceHelper.prototype.exitVR = function () {
  94017. if (this.onExitingVRObservable) {
  94018. try {
  94019. this.onExitingVRObservable.notifyObservers(this);
  94020. }
  94021. catch (err) {
  94022. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  94023. }
  94024. }
  94025. if (this._webVRpresenting) {
  94026. this._scene.getEngine().disableVR();
  94027. }
  94028. if (this._scene.activeCamera) {
  94029. this._position = this._scene.activeCamera.position.clone();
  94030. }
  94031. if (this._deviceOrientationCamera) {
  94032. this._deviceOrientationCamera.position = this._position;
  94033. this._scene.activeCamera = this._deviceOrientationCamera;
  94034. if (this._canvas) {
  94035. this._scene.activeCamera.attachControl(this._canvas);
  94036. }
  94037. }
  94038. else if (this._existingCamera) {
  94039. this._existingCamera.position = this._position;
  94040. this._scene.activeCamera = this._existingCamera;
  94041. }
  94042. this.updateButtonVisibility();
  94043. if (this._interactionsEnabled) {
  94044. this._scene.unregisterBeforeRender(this.beforeRender);
  94045. }
  94046. // resize to update width and height when exiting vr exits fullscreen
  94047. this._scene.getEngine().resize();
  94048. };
  94049. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  94050. /**
  94051. * The position of the vr experience helper.
  94052. */
  94053. get: function () {
  94054. return this._position;
  94055. },
  94056. /**
  94057. * Sets the position of the vr experience helper.
  94058. */
  94059. set: function (value) {
  94060. this._position = value;
  94061. if (this._scene.activeCamera) {
  94062. this._scene.activeCamera.position = value;
  94063. }
  94064. },
  94065. enumerable: true,
  94066. configurable: true
  94067. });
  94068. /**
  94069. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  94070. */
  94071. VRExperienceHelper.prototype.enableInteractions = function () {
  94072. var _this = this;
  94073. if (!this._interactionsEnabled) {
  94074. this._interactionsRequested = true;
  94075. if (this.leftController) {
  94076. this._enableInteractionOnController(this.leftController);
  94077. }
  94078. if (this.rightController) {
  94079. this._enableInteractionOnController(this.rightController);
  94080. }
  94081. this.raySelectionPredicate = function (mesh) {
  94082. return mesh.isVisible && mesh.isPickable;
  94083. };
  94084. this.meshSelectionPredicate = function (mesh) {
  94085. return true;
  94086. };
  94087. this._raySelectionPredicate = function (mesh) {
  94088. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  94089. && mesh.name.indexOf("teleportationTarget") === -1
  94090. && mesh.name.indexOf("torusTeleportation") === -1)) {
  94091. return _this.raySelectionPredicate(mesh);
  94092. }
  94093. return false;
  94094. };
  94095. this._interactionsEnabled = true;
  94096. }
  94097. };
  94098. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  94099. get: function () {
  94100. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  94101. },
  94102. enumerable: true,
  94103. configurable: true
  94104. });
  94105. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  94106. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  94107. if (this._floorMeshesCollection[i].id === mesh.id) {
  94108. return true;
  94109. }
  94110. }
  94111. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  94112. return true;
  94113. }
  94114. return false;
  94115. };
  94116. /**
  94117. * Adds a floor mesh to be used for teleportation.
  94118. * @param floorMesh the mesh to be used for teleportation.
  94119. */
  94120. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  94121. if (!this._floorMeshesCollection) {
  94122. return;
  94123. }
  94124. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  94125. return;
  94126. }
  94127. this._floorMeshesCollection.push(floorMesh);
  94128. };
  94129. /**
  94130. * Removes a floor mesh from being used for teleportation.
  94131. * @param floorMesh the mesh to be removed.
  94132. */
  94133. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  94134. if (!this._floorMeshesCollection) {
  94135. return;
  94136. }
  94137. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  94138. if (meshIndex !== -1) {
  94139. this._floorMeshesCollection.splice(meshIndex, 1);
  94140. }
  94141. };
  94142. /**
  94143. * Enables interactions and teleportation using the VR controllers and gaze.
  94144. * @param vrTeleportationOptions options to modify teleportation behavior.
  94145. */
  94146. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  94147. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  94148. if (!this._teleportationInitialized) {
  94149. this._teleportationRequested = true;
  94150. this.enableInteractions();
  94151. if (vrTeleportationOptions.floorMeshName) {
  94152. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  94153. }
  94154. if (vrTeleportationOptions.floorMeshes) {
  94155. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  94156. }
  94157. if (this.leftController != null) {
  94158. this._enableTeleportationOnController(this.leftController);
  94159. }
  94160. if (this.rightController != null) {
  94161. this._enableTeleportationOnController(this.rightController);
  94162. }
  94163. // Creates an image processing post process for the vignette not relying
  94164. // on the main scene configuration for image processing to reduce setup and spaces
  94165. // (gamma/linear) conflicts.
  94166. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  94167. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  94168. imageProcessingConfiguration.vignetteEnabled = true;
  94169. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  94170. this._webVRCamera.detachPostProcess(this._postProcessMove);
  94171. this._teleportationInitialized = true;
  94172. if (this._isDefaultTeleportationTarget) {
  94173. this._createTeleportationCircles();
  94174. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  94175. }
  94176. }
  94177. };
  94178. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  94179. var _this = this;
  94180. var controllerMesh = controller.webVRController.mesh;
  94181. if (controllerMesh) {
  94182. controller._interactionsEnabled = true;
  94183. controller._activatePointer();
  94184. if (this.webVROptions.laserToggle) {
  94185. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  94186. // Enabling / disabling laserPointer
  94187. if (_this._displayLaserPointer && stateObject.value === 1) {
  94188. if (controller._activePointer) {
  94189. controller._deactivatePointer();
  94190. }
  94191. else {
  94192. controller._activatePointer();
  94193. }
  94194. if (_this.displayGaze) {
  94195. controller._gazeTracker.isVisible = controller._activePointer;
  94196. }
  94197. }
  94198. });
  94199. }
  94200. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  94201. var gazer = controller;
  94202. if (_this._noControllerIsActive) {
  94203. gazer = _this._cameraGazer;
  94204. }
  94205. if (!gazer._pointerDownOnMeshAsked) {
  94206. if (stateObject.value > _this._padSensibilityUp) {
  94207. gazer._selectionPointerDown();
  94208. }
  94209. }
  94210. else if (stateObject.value < _this._padSensibilityDown) {
  94211. gazer._selectionPointerUp();
  94212. }
  94213. });
  94214. }
  94215. };
  94216. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  94217. // Dont teleport if another gaze already requested teleportation
  94218. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  94219. return;
  94220. }
  94221. if (!gazer._teleportationRequestInitiated) {
  94222. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  94223. gazer._activatePointer();
  94224. gazer._teleportationRequestInitiated = true;
  94225. }
  94226. }
  94227. else {
  94228. // Listening to the proper controller values changes to confirm teleportation
  94229. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  94230. if (this._teleportActive) {
  94231. this._teleportCamera(this._haloCenter);
  94232. }
  94233. gazer._teleportationRequestInitiated = false;
  94234. }
  94235. }
  94236. };
  94237. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  94238. // Only rotate when user is not currently selecting a teleportation location
  94239. if (gazer._teleportationRequestInitiated) {
  94240. return;
  94241. }
  94242. if (!gazer._rotationLeftAsked) {
  94243. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  94244. gazer._rotationLeftAsked = true;
  94245. if (this._rotationAllowed) {
  94246. this._rotateCamera(false);
  94247. }
  94248. }
  94249. }
  94250. else {
  94251. if (stateObject.x > -this._padSensibilityDown) {
  94252. gazer._rotationLeftAsked = false;
  94253. }
  94254. }
  94255. if (!gazer._rotationRightAsked) {
  94256. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  94257. gazer._rotationRightAsked = true;
  94258. if (this._rotationAllowed) {
  94259. this._rotateCamera(true);
  94260. }
  94261. }
  94262. }
  94263. else {
  94264. if (stateObject.x < this._padSensibilityDown) {
  94265. gazer._rotationRightAsked = false;
  94266. }
  94267. }
  94268. };
  94269. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  94270. // Only teleport backwards when user is not currently selecting a teleportation location
  94271. if (gazer._teleportationRequestInitiated) {
  94272. return;
  94273. }
  94274. // Teleport backwards
  94275. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  94276. if (!gazer._teleportationBackRequestInitiated) {
  94277. if (!this.currentVRCamera) {
  94278. return;
  94279. }
  94280. // Get rotation and position of the current camera
  94281. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  94282. var position = this.currentVRCamera.position;
  94283. // If the camera has device position, use that instead
  94284. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  94285. rotation = this.currentVRCamera.deviceRotationQuaternion;
  94286. position = this.currentVRCamera.devicePosition;
  94287. }
  94288. // Get matrix with only the y rotation of the device rotation
  94289. rotation.toEulerAnglesToRef(this._workingVector);
  94290. this._workingVector.z = 0;
  94291. this._workingVector.x = 0;
  94292. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  94293. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  94294. // Rotate backwards ray by device rotation to cast at the ground behind the user
  94295. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  94296. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  94297. var ray = new BABYLON.Ray(position, this._workingVector);
  94298. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94299. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  94300. this._teleportCamera(hit.pickedPoint);
  94301. }
  94302. gazer._teleportationBackRequestInitiated = true;
  94303. }
  94304. }
  94305. else {
  94306. gazer._teleportationBackRequestInitiated = false;
  94307. }
  94308. };
  94309. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  94310. var _this = this;
  94311. var controllerMesh = controller.webVRController.mesh;
  94312. if (controllerMesh) {
  94313. if (!controller._interactionsEnabled) {
  94314. this._enableInteractionOnController(controller);
  94315. }
  94316. controller._interactionsEnabled = true;
  94317. controller._teleportationEnabled = true;
  94318. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94319. controller._dpadPressed = false;
  94320. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  94321. controller._dpadPressed = stateObject.pressed;
  94322. if (!controller._dpadPressed) {
  94323. controller._rotationLeftAsked = false;
  94324. controller._rotationRightAsked = false;
  94325. controller._teleportationBackRequestInitiated = false;
  94326. }
  94327. });
  94328. }
  94329. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  94330. if (_this.teleportationEnabled) {
  94331. _this._checkTeleportBackwards(stateObject, controller);
  94332. _this._checkTeleportWithRay(stateObject, controller);
  94333. }
  94334. _this._checkRotate(stateObject, controller);
  94335. });
  94336. }
  94337. };
  94338. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  94339. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  94340. this._teleportationTarget.isPickable = false;
  94341. var length = 512;
  94342. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  94343. dynamicTexture.hasAlpha = true;
  94344. var context = dynamicTexture.getContext();
  94345. var centerX = length / 2;
  94346. var centerY = length / 2;
  94347. var radius = 200;
  94348. context.beginPath();
  94349. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  94350. context.fillStyle = this._teleportationFillColor;
  94351. context.fill();
  94352. context.lineWidth = 10;
  94353. context.strokeStyle = this._teleportationBorderColor;
  94354. context.stroke();
  94355. context.closePath();
  94356. dynamicTexture.update();
  94357. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  94358. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  94359. this._teleportationTarget.material = teleportationCircleMaterial;
  94360. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  94361. torus.isPickable = false;
  94362. torus.parent = this._teleportationTarget;
  94363. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  94364. var keys = [];
  94365. keys.push({
  94366. frame: 0,
  94367. value: 0
  94368. });
  94369. keys.push({
  94370. frame: 30,
  94371. value: 0.4
  94372. });
  94373. keys.push({
  94374. frame: 60,
  94375. value: 0
  94376. });
  94377. animationInnerCircle.setKeys(keys);
  94378. var easingFunction = new BABYLON.SineEase();
  94379. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94380. animationInnerCircle.setEasingFunction(easingFunction);
  94381. torus.animations = [];
  94382. torus.animations.push(animationInnerCircle);
  94383. this._scene.beginAnimation(torus, 0, 60, true);
  94384. this._hideTeleportationTarget();
  94385. };
  94386. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  94387. this._teleportActive = true;
  94388. if (this._teleportationInitialized) {
  94389. this._teleportationTarget.isVisible = true;
  94390. if (this._isDefaultTeleportationTarget) {
  94391. this._teleportationTarget.getChildren()[0].isVisible = true;
  94392. }
  94393. }
  94394. };
  94395. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  94396. this._teleportActive = false;
  94397. if (this._teleportationInitialized) {
  94398. this._teleportationTarget.isVisible = false;
  94399. if (this._isDefaultTeleportationTarget) {
  94400. this._teleportationTarget.getChildren()[0].isVisible = false;
  94401. }
  94402. }
  94403. };
  94404. VRExperienceHelper.prototype._rotateCamera = function (right) {
  94405. var _this = this;
  94406. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94407. return;
  94408. }
  94409. if (right) {
  94410. this._rotationAngle++;
  94411. }
  94412. else {
  94413. this._rotationAngle--;
  94414. }
  94415. this.currentVRCamera.animations = [];
  94416. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  94417. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94418. var animationRotationKeys = [];
  94419. animationRotationKeys.push({
  94420. frame: 0,
  94421. value: this.currentVRCamera.rotationQuaternion
  94422. });
  94423. animationRotationKeys.push({
  94424. frame: 6,
  94425. value: target
  94426. });
  94427. animationRotation.setKeys(animationRotationKeys);
  94428. animationRotation.setEasingFunction(this._circleEase);
  94429. this.currentVRCamera.animations.push(animationRotation);
  94430. this._postProcessMove.animations = [];
  94431. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94432. var vignetteWeightKeys = [];
  94433. vignetteWeightKeys.push({
  94434. frame: 0,
  94435. value: 0
  94436. });
  94437. vignetteWeightKeys.push({
  94438. frame: 3,
  94439. value: 4
  94440. });
  94441. vignetteWeightKeys.push({
  94442. frame: 6,
  94443. value: 0
  94444. });
  94445. animationPP.setKeys(vignetteWeightKeys);
  94446. animationPP.setEasingFunction(this._circleEase);
  94447. this._postProcessMove.animations.push(animationPP);
  94448. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94449. var vignetteStretchKeys = [];
  94450. vignetteStretchKeys.push({
  94451. frame: 0,
  94452. value: 0
  94453. });
  94454. vignetteStretchKeys.push({
  94455. frame: 3,
  94456. value: 10
  94457. });
  94458. vignetteStretchKeys.push({
  94459. frame: 6,
  94460. value: 0
  94461. });
  94462. animationPP2.setKeys(vignetteStretchKeys);
  94463. animationPP2.setEasingFunction(this._circleEase);
  94464. this._postProcessMove.animations.push(animationPP2);
  94465. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94466. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94467. this._postProcessMove.samples = 4;
  94468. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94469. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  94470. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94471. });
  94472. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  94473. };
  94474. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  94475. if (hit.pickedPoint) {
  94476. if (gazer._teleportationRequestInitiated) {
  94477. this._displayTeleportationTarget();
  94478. this._haloCenter.copyFrom(hit.pickedPoint);
  94479. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  94480. }
  94481. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  94482. if (pickNormal) {
  94483. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94484. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94485. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  94486. }
  94487. this._teleportationTarget.position.y += 0.1;
  94488. }
  94489. };
  94490. VRExperienceHelper.prototype._teleportCamera = function (location) {
  94491. var _this = this;
  94492. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94493. return;
  94494. }
  94495. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  94496. // offset of the headset from the anchor.
  94497. if (this.webVRCamera.leftCamera) {
  94498. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  94499. this._workingVector.subtractInPlace(this.webVRCamera.position);
  94500. location.subtractToRef(this._workingVector, this._workingVector);
  94501. }
  94502. else {
  94503. this._workingVector.copyFrom(location);
  94504. }
  94505. // Add height to account for user's height offset
  94506. if (this.isInVRMode) {
  94507. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  94508. }
  94509. else {
  94510. this._workingVector.y += this._defaultHeight;
  94511. }
  94512. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  94513. // Create animation from the camera's position to the new location
  94514. this.currentVRCamera.animations = [];
  94515. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94516. var animationCameraTeleportationKeys = [{
  94517. frame: 0,
  94518. value: this.currentVRCamera.position
  94519. },
  94520. {
  94521. frame: 11,
  94522. value: this._workingVector
  94523. }
  94524. ];
  94525. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  94526. animationCameraTeleportation.setEasingFunction(this._circleEase);
  94527. this.currentVRCamera.animations.push(animationCameraTeleportation);
  94528. this._postProcessMove.animations = [];
  94529. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94530. var vignetteWeightKeys = [];
  94531. vignetteWeightKeys.push({
  94532. frame: 0,
  94533. value: 0
  94534. });
  94535. vignetteWeightKeys.push({
  94536. frame: 5,
  94537. value: 8
  94538. });
  94539. vignetteWeightKeys.push({
  94540. frame: 11,
  94541. value: 0
  94542. });
  94543. animationPP.setKeys(vignetteWeightKeys);
  94544. this._postProcessMove.animations.push(animationPP);
  94545. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94546. var vignetteStretchKeys = [];
  94547. vignetteStretchKeys.push({
  94548. frame: 0,
  94549. value: 0
  94550. });
  94551. vignetteStretchKeys.push({
  94552. frame: 5,
  94553. value: 10
  94554. });
  94555. vignetteStretchKeys.push({
  94556. frame: 11,
  94557. value: 0
  94558. });
  94559. animationPP2.setKeys(vignetteStretchKeys);
  94560. this._postProcessMove.animations.push(animationPP2);
  94561. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94562. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94563. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94564. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  94565. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94566. });
  94567. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  94568. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  94569. });
  94570. this._hideTeleportationTarget();
  94571. };
  94572. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  94573. if (normal) {
  94574. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  94575. if (angle < Math.PI / 2) {
  94576. normal.scaleInPlace(-1);
  94577. }
  94578. }
  94579. return normal;
  94580. };
  94581. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  94582. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94583. return;
  94584. }
  94585. var ray = gazer._getForwardRay(this._rayLength);
  94586. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94587. if (hit) {
  94588. // Populate the contrllers mesh that can be used for drag/drop
  94589. if (gazer._laserPointer) {
  94590. hit.originMesh = gazer._laserPointer.parent;
  94591. }
  94592. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  94593. }
  94594. gazer._currentHit = hit;
  94595. // Moving the gazeTracker on the mesh face targetted
  94596. if (hit && hit.pickedPoint) {
  94597. if (this._displayGaze) {
  94598. var multiplier = 1;
  94599. gazer._gazeTracker.isVisible = true;
  94600. if (gazer._isActionableMesh) {
  94601. multiplier = 3;
  94602. }
  94603. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  94604. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  94605. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  94606. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  94607. // To avoid z-fighting
  94608. var deltaFighting = 0.002;
  94609. if (pickNormal) {
  94610. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94611. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94612. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  94613. }
  94614. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  94615. if (gazer._gazeTracker.position.x < 0) {
  94616. gazer._gazeTracker.position.x += deltaFighting;
  94617. }
  94618. else {
  94619. gazer._gazeTracker.position.x -= deltaFighting;
  94620. }
  94621. if (gazer._gazeTracker.position.y < 0) {
  94622. gazer._gazeTracker.position.y += deltaFighting;
  94623. }
  94624. else {
  94625. gazer._gazeTracker.position.y -= deltaFighting;
  94626. }
  94627. if (gazer._gazeTracker.position.z < 0) {
  94628. gazer._gazeTracker.position.z += deltaFighting;
  94629. }
  94630. else {
  94631. gazer._gazeTracker.position.z -= deltaFighting;
  94632. }
  94633. }
  94634. // Changing the size of the laser pointer based on the distance from the targetted point
  94635. gazer._updatePointerDistance(hit.distance);
  94636. }
  94637. else {
  94638. gazer._updatePointerDistance();
  94639. gazer._gazeTracker.isVisible = false;
  94640. }
  94641. if (hit && hit.pickedMesh) {
  94642. // The object selected is the floor, we're in a teleportation scenario
  94643. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  94644. // Moving the teleportation area to this targetted point
  94645. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  94646. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  94647. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94648. }
  94649. gazer._currentMeshSelected = null;
  94650. if (gazer._teleportationRequestInitiated) {
  94651. this._moveTeleportationSelectorTo(hit, gazer, ray);
  94652. }
  94653. return;
  94654. }
  94655. // If not, we're in a selection scenario
  94656. //this._teleportationAllowed = false;
  94657. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  94658. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  94659. this.onNewMeshPicked.notifyObservers(hit);
  94660. gazer._currentMeshSelected = hit.pickedMesh;
  94661. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  94662. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  94663. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  94664. gazer._isActionableMesh = true;
  94665. }
  94666. else {
  94667. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94668. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94669. gazer._isActionableMesh = false;
  94670. }
  94671. try {
  94672. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  94673. }
  94674. catch (err) {
  94675. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  94676. }
  94677. }
  94678. else {
  94679. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94680. gazer._currentMeshSelected = null;
  94681. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94682. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94683. }
  94684. }
  94685. }
  94686. else {
  94687. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94688. gazer._currentMeshSelected = null;
  94689. //this._teleportationAllowed = false;
  94690. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94691. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94692. }
  94693. };
  94694. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  94695. if (mesh) {
  94696. this.onSelectedMeshUnselected.notifyObservers(mesh);
  94697. }
  94698. };
  94699. /**
  94700. * Sets the color of the laser ray from the vr controllers.
  94701. * @param color new color for the ray.
  94702. */
  94703. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  94704. if (this.leftController) {
  94705. this.leftController._setLaserPointerColor(color);
  94706. }
  94707. if (this.rightController) {
  94708. this.rightController._setLaserPointerColor(color);
  94709. }
  94710. };
  94711. /**
  94712. * Sets the color of the ray from the vr headsets gaze.
  94713. * @param color new color for the ray.
  94714. */
  94715. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  94716. if (!this._cameraGazer._gazeTracker.material) {
  94717. return;
  94718. }
  94719. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  94720. if (this.leftController) {
  94721. this.leftController._gazeTracker.material.emissiveColor = color;
  94722. }
  94723. if (this.rightController) {
  94724. this.rightController._gazeTracker.material.emissiveColor = color;
  94725. }
  94726. };
  94727. /**
  94728. * Exits VR and disposes of the vr experience helper
  94729. */
  94730. VRExperienceHelper.prototype.dispose = function () {
  94731. if (this.isInVRMode) {
  94732. this.exitVR();
  94733. }
  94734. if (this._postProcessMove) {
  94735. this._postProcessMove.dispose();
  94736. }
  94737. if (this._webVRCamera) {
  94738. this._webVRCamera.dispose();
  94739. }
  94740. if (this._vrDeviceOrientationCamera) {
  94741. this._vrDeviceOrientationCamera.dispose();
  94742. }
  94743. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  94744. document.body.removeChild(this._btnVR);
  94745. }
  94746. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  94747. this._deviceOrientationCamera.dispose();
  94748. }
  94749. if (this._cameraGazer) {
  94750. this._cameraGazer.dispose();
  94751. }
  94752. if (this.leftController) {
  94753. this.leftController.dispose();
  94754. }
  94755. if (this.rightController) {
  94756. this.rightController.dispose();
  94757. }
  94758. if (this._teleportationTarget) {
  94759. this._teleportationTarget.dispose();
  94760. }
  94761. this._floorMeshesCollection = [];
  94762. document.removeEventListener("keydown", this._onKeyDown);
  94763. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94764. window.removeEventListener("resize", this._onResize);
  94765. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  94766. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  94767. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  94768. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  94769. document.onmsfullscreenchange = null;
  94770. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  94771. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  94772. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  94773. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94774. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  94775. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  94776. this._scene.unregisterBeforeRender(this.beforeRender);
  94777. };
  94778. /**
  94779. * Gets the name of the VRExperienceHelper class
  94780. * @returns "VRExperienceHelper"
  94781. */
  94782. VRExperienceHelper.prototype.getClassName = function () {
  94783. return "VRExperienceHelper";
  94784. };
  94785. return VRExperienceHelper;
  94786. }());
  94787. BABYLON.VRExperienceHelper = VRExperienceHelper;
  94788. })(BABYLON || (BABYLON = {}));
  94789. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  94790. // Mainly based on these 2 articles :
  94791. // 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
  94792. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  94793. var BABYLON;
  94794. (function (BABYLON) {
  94795. /**
  94796. * Defines the potential axis of a Joystick
  94797. */
  94798. var JoystickAxis;
  94799. (function (JoystickAxis) {
  94800. /** X axis */
  94801. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  94802. /** Y axis */
  94803. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  94804. /** Z axis */
  94805. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  94806. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  94807. /**
  94808. * Class used to define virtual joystick (used in touch mode)
  94809. */
  94810. var VirtualJoystick = /** @class */ (function () {
  94811. /**
  94812. * Creates a new virtual joystick
  94813. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94814. */
  94815. function VirtualJoystick(leftJoystick) {
  94816. var _this = this;
  94817. if (leftJoystick) {
  94818. this._leftJoystick = true;
  94819. }
  94820. else {
  94821. this._leftJoystick = false;
  94822. }
  94823. VirtualJoystick._globalJoystickIndex++;
  94824. // By default left & right arrow keys are moving the X
  94825. // and up & down keys are moving the Y
  94826. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94827. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94828. this.reverseLeftRight = false;
  94829. this.reverseUpDown = false;
  94830. // collections of pointers
  94831. this._touches = new BABYLON.StringDictionary();
  94832. this.deltaPosition = BABYLON.Vector3.Zero();
  94833. this._joystickSensibility = 25;
  94834. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94835. this._onResize = function (evt) {
  94836. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94837. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94838. if (VirtualJoystick.vjCanvas) {
  94839. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94840. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94841. }
  94842. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94843. };
  94844. // injecting a canvas element on top of the canvas 3D game
  94845. if (!VirtualJoystick.vjCanvas) {
  94846. window.addEventListener("resize", this._onResize, false);
  94847. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94848. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94849. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94850. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94851. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94852. VirtualJoystick.vjCanvas.style.width = "100%";
  94853. VirtualJoystick.vjCanvas.style.height = "100%";
  94854. VirtualJoystick.vjCanvas.style.position = "absolute";
  94855. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94856. VirtualJoystick.vjCanvas.style.top = "0px";
  94857. VirtualJoystick.vjCanvas.style.left = "0px";
  94858. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94859. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94860. // Support for jQuery PEP polyfill
  94861. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94862. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94863. if (!context) {
  94864. throw new Error("Unable to create canvas for virtual joystick");
  94865. }
  94866. VirtualJoystick.vjCanvasContext = context;
  94867. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94868. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94869. document.body.appendChild(VirtualJoystick.vjCanvas);
  94870. }
  94871. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94872. this.pressed = false;
  94873. // default joystick color
  94874. this._joystickColor = "cyan";
  94875. this._joystickPointerID = -1;
  94876. // current joystick position
  94877. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94878. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94879. // origin joystick position
  94880. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94881. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94882. this._onPointerDownHandlerRef = function (evt) {
  94883. _this._onPointerDown(evt);
  94884. };
  94885. this._onPointerMoveHandlerRef = function (evt) {
  94886. _this._onPointerMove(evt);
  94887. };
  94888. this._onPointerUpHandlerRef = function (evt) {
  94889. _this._onPointerUp(evt);
  94890. };
  94891. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94892. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94893. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94894. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94895. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94896. evt.preventDefault(); // Disables system menu
  94897. }, false);
  94898. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94899. }
  94900. /**
  94901. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94902. * @param newJoystickSensibility defines the new sensibility
  94903. */
  94904. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94905. this._joystickSensibility = newJoystickSensibility;
  94906. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94907. };
  94908. VirtualJoystick.prototype._onPointerDown = function (e) {
  94909. var positionOnScreenCondition;
  94910. e.preventDefault();
  94911. if (this._leftJoystick === true) {
  94912. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94913. }
  94914. else {
  94915. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94916. }
  94917. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94918. // First contact will be dedicated to the virtual joystick
  94919. this._joystickPointerID = e.pointerId;
  94920. this._joystickPointerStartPos.x = e.clientX;
  94921. this._joystickPointerStartPos.y = e.clientY;
  94922. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94923. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94924. this._deltaJoystickVector.x = 0;
  94925. this._deltaJoystickVector.y = 0;
  94926. this.pressed = true;
  94927. this._touches.add(e.pointerId.toString(), e);
  94928. }
  94929. else {
  94930. // You can only trigger the action buttons with a joystick declared
  94931. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94932. this._action();
  94933. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94934. }
  94935. }
  94936. };
  94937. VirtualJoystick.prototype._onPointerMove = function (e) {
  94938. // If the current pointer is the one associated to the joystick (first touch contact)
  94939. if (this._joystickPointerID == e.pointerId) {
  94940. this._joystickPointerPos.x = e.clientX;
  94941. this._joystickPointerPos.y = e.clientY;
  94942. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94943. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94944. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94945. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94946. switch (this._axisTargetedByLeftAndRight) {
  94947. case JoystickAxis.X:
  94948. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94949. break;
  94950. case JoystickAxis.Y:
  94951. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94952. break;
  94953. case JoystickAxis.Z:
  94954. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94955. break;
  94956. }
  94957. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94958. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94959. switch (this._axisTargetedByUpAndDown) {
  94960. case JoystickAxis.X:
  94961. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94962. break;
  94963. case JoystickAxis.Y:
  94964. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94965. break;
  94966. case JoystickAxis.Z:
  94967. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94968. break;
  94969. }
  94970. }
  94971. else {
  94972. var data = this._touches.get(e.pointerId.toString());
  94973. if (data) {
  94974. data.x = e.clientX;
  94975. data.y = e.clientY;
  94976. }
  94977. }
  94978. };
  94979. VirtualJoystick.prototype._onPointerUp = function (e) {
  94980. if (this._joystickPointerID == e.pointerId) {
  94981. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94982. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94983. this._joystickPointerID = -1;
  94984. this.pressed = false;
  94985. }
  94986. else {
  94987. var touch = this._touches.get(e.pointerId.toString());
  94988. if (touch) {
  94989. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94990. }
  94991. }
  94992. this._deltaJoystickVector.x = 0;
  94993. this._deltaJoystickVector.y = 0;
  94994. this._touches.remove(e.pointerId.toString());
  94995. };
  94996. /**
  94997. * Change the color of the virtual joystick
  94998. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94999. */
  95000. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  95001. this._joystickColor = newColor;
  95002. };
  95003. /**
  95004. * Defines a callback to call when the joystick is touched
  95005. * @param action defines the callback
  95006. */
  95007. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  95008. this._action = action;
  95009. };
  95010. /**
  95011. * Defines which axis you'd like to control for left & right
  95012. * @param axis defines the axis to use
  95013. */
  95014. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  95015. switch (axis) {
  95016. case JoystickAxis.X:
  95017. case JoystickAxis.Y:
  95018. case JoystickAxis.Z:
  95019. this._axisTargetedByLeftAndRight = axis;
  95020. break;
  95021. default:
  95022. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  95023. break;
  95024. }
  95025. };
  95026. /**
  95027. * Defines which axis you'd like to control for up & down
  95028. * @param axis defines the axis to use
  95029. */
  95030. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  95031. switch (axis) {
  95032. case JoystickAxis.X:
  95033. case JoystickAxis.Y:
  95034. case JoystickAxis.Z:
  95035. this._axisTargetedByUpAndDown = axis;
  95036. break;
  95037. default:
  95038. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95039. break;
  95040. }
  95041. };
  95042. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  95043. var _this = this;
  95044. if (this.pressed) {
  95045. this._touches.forEach(function (key, touch) {
  95046. if (touch.pointerId === _this._joystickPointerID) {
  95047. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  95048. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  95049. VirtualJoystick.vjCanvasContext.beginPath();
  95050. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95051. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95052. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  95053. VirtualJoystick.vjCanvasContext.stroke();
  95054. VirtualJoystick.vjCanvasContext.closePath();
  95055. VirtualJoystick.vjCanvasContext.beginPath();
  95056. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95057. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95058. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  95059. VirtualJoystick.vjCanvasContext.stroke();
  95060. VirtualJoystick.vjCanvasContext.closePath();
  95061. VirtualJoystick.vjCanvasContext.beginPath();
  95062. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95063. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  95064. VirtualJoystick.vjCanvasContext.stroke();
  95065. VirtualJoystick.vjCanvasContext.closePath();
  95066. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  95067. }
  95068. else {
  95069. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95070. VirtualJoystick.vjCanvasContext.beginPath();
  95071. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  95072. VirtualJoystick.vjCanvasContext.beginPath();
  95073. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  95074. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95075. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  95076. VirtualJoystick.vjCanvasContext.stroke();
  95077. VirtualJoystick.vjCanvasContext.closePath();
  95078. touch.prevX = touch.x;
  95079. touch.prevY = touch.y;
  95080. }
  95081. ;
  95082. });
  95083. }
  95084. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95085. };
  95086. /**
  95087. * Release internal HTML canvas
  95088. */
  95089. VirtualJoystick.prototype.releaseCanvas = function () {
  95090. if (VirtualJoystick.vjCanvas) {
  95091. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  95092. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  95093. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  95094. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  95095. window.removeEventListener("resize", this._onResize);
  95096. document.body.removeChild(VirtualJoystick.vjCanvas);
  95097. VirtualJoystick.vjCanvas = null;
  95098. }
  95099. };
  95100. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  95101. VirtualJoystick._globalJoystickIndex = 0;
  95102. return VirtualJoystick;
  95103. }());
  95104. BABYLON.VirtualJoystick = VirtualJoystick;
  95105. })(BABYLON || (BABYLON = {}));
  95106. //# sourceMappingURL=babylon.virtualJoystick.js.map
  95107. var BABYLON;
  95108. (function (BABYLON) {
  95109. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  95110. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  95111. });
  95112. // We're mainly based on the logic defined into the FreeCamera code
  95113. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  95114. __extends(VirtualJoysticksCamera, _super);
  95115. function VirtualJoysticksCamera(name, position, scene) {
  95116. var _this = _super.call(this, name, position, scene) || this;
  95117. _this.inputs.addVirtualJoystick();
  95118. return _this;
  95119. }
  95120. VirtualJoysticksCamera.prototype.getClassName = function () {
  95121. return "VirtualJoysticksCamera";
  95122. };
  95123. return VirtualJoysticksCamera;
  95124. }(BABYLON.FreeCamera));
  95125. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  95126. })(BABYLON || (BABYLON = {}));
  95127. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  95128. var BABYLON;
  95129. (function (BABYLON) {
  95130. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  95131. function FreeCameraVirtualJoystickInput() {
  95132. }
  95133. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  95134. return this._leftjoystick;
  95135. };
  95136. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  95137. return this._rightjoystick;
  95138. };
  95139. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  95140. if (this._leftjoystick) {
  95141. var camera = this.camera;
  95142. var speed = camera._computeLocalCameraSpeed() * 50;
  95143. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  95144. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  95145. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  95146. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  95147. if (!this._leftjoystick.pressed) {
  95148. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  95149. }
  95150. if (!this._rightjoystick.pressed) {
  95151. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  95152. }
  95153. }
  95154. };
  95155. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  95156. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  95157. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  95158. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  95159. this._leftjoystick.setJoystickSensibility(0.15);
  95160. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  95161. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  95162. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  95163. this._rightjoystick.reverseUpDown = true;
  95164. this._rightjoystick.setJoystickSensibility(0.05);
  95165. this._rightjoystick.setJoystickColor("yellow");
  95166. };
  95167. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  95168. this._leftjoystick.releaseCanvas();
  95169. this._rightjoystick.releaseCanvas();
  95170. };
  95171. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  95172. return "FreeCameraVirtualJoystickInput";
  95173. };
  95174. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  95175. return "virtualJoystick";
  95176. };
  95177. return FreeCameraVirtualJoystickInput;
  95178. }());
  95179. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  95180. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  95181. })(BABYLON || (BABYLON = {}));
  95182. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  95183. var BABYLON;
  95184. (function (BABYLON) {
  95185. var SimplificationSettings = /** @class */ (function () {
  95186. function SimplificationSettings(quality, distance, optimizeMesh) {
  95187. this.quality = quality;
  95188. this.distance = distance;
  95189. this.optimizeMesh = optimizeMesh;
  95190. }
  95191. return SimplificationSettings;
  95192. }());
  95193. BABYLON.SimplificationSettings = SimplificationSettings;
  95194. var SimplificationQueue = /** @class */ (function () {
  95195. function SimplificationQueue() {
  95196. this.running = false;
  95197. this._simplificationArray = [];
  95198. }
  95199. SimplificationQueue.prototype.addTask = function (task) {
  95200. this._simplificationArray.push(task);
  95201. };
  95202. SimplificationQueue.prototype.executeNext = function () {
  95203. var task = this._simplificationArray.pop();
  95204. if (task) {
  95205. this.running = true;
  95206. this.runSimplification(task);
  95207. }
  95208. else {
  95209. this.running = false;
  95210. }
  95211. };
  95212. SimplificationQueue.prototype.runSimplification = function (task) {
  95213. var _this = this;
  95214. if (task.parallelProcessing) {
  95215. //parallel simplifier
  95216. task.settings.forEach(function (setting) {
  95217. var simplifier = _this.getSimplifier(task);
  95218. simplifier.simplify(setting, function (newMesh) {
  95219. task.mesh.addLODLevel(setting.distance, newMesh);
  95220. newMesh.isVisible = true;
  95221. //check if it is the last
  95222. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  95223. //all done, run the success callback.
  95224. task.successCallback();
  95225. }
  95226. _this.executeNext();
  95227. });
  95228. });
  95229. }
  95230. else {
  95231. //single simplifier.
  95232. var simplifier = this.getSimplifier(task);
  95233. var runDecimation = function (setting, callback) {
  95234. simplifier.simplify(setting, function (newMesh) {
  95235. task.mesh.addLODLevel(setting.distance, newMesh);
  95236. newMesh.isVisible = true;
  95237. //run the next quality level
  95238. callback();
  95239. });
  95240. };
  95241. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  95242. runDecimation(task.settings[loop.index], function () {
  95243. loop.executeNext();
  95244. });
  95245. }, function () {
  95246. //execution ended, run the success callback.
  95247. if (task.successCallback) {
  95248. task.successCallback();
  95249. }
  95250. _this.executeNext();
  95251. });
  95252. }
  95253. };
  95254. SimplificationQueue.prototype.getSimplifier = function (task) {
  95255. switch (task.simplificationType) {
  95256. case SimplificationType.QUADRATIC:
  95257. default:
  95258. return new QuadraticErrorSimplification(task.mesh);
  95259. }
  95260. };
  95261. return SimplificationQueue;
  95262. }());
  95263. BABYLON.SimplificationQueue = SimplificationQueue;
  95264. /**
  95265. * The implemented types of simplification
  95266. * At the moment only Quadratic Error Decimation is implemented
  95267. */
  95268. var SimplificationType;
  95269. (function (SimplificationType) {
  95270. /** Quadratic error decimation */
  95271. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  95272. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  95273. var DecimationTriangle = /** @class */ (function () {
  95274. function DecimationTriangle(vertices) {
  95275. this.vertices = vertices;
  95276. this.error = new Array(4);
  95277. this.deleted = false;
  95278. this.isDirty = false;
  95279. this.deletePending = false;
  95280. this.borderFactor = 0;
  95281. }
  95282. return DecimationTriangle;
  95283. }());
  95284. BABYLON.DecimationTriangle = DecimationTriangle;
  95285. var DecimationVertex = /** @class */ (function () {
  95286. function DecimationVertex(position, id) {
  95287. this.position = position;
  95288. this.id = id;
  95289. this.isBorder = true;
  95290. this.q = new QuadraticMatrix();
  95291. this.triangleCount = 0;
  95292. this.triangleStart = 0;
  95293. this.originalOffsets = [];
  95294. }
  95295. DecimationVertex.prototype.updatePosition = function (newPosition) {
  95296. this.position.copyFrom(newPosition);
  95297. };
  95298. return DecimationVertex;
  95299. }());
  95300. BABYLON.DecimationVertex = DecimationVertex;
  95301. var QuadraticMatrix = /** @class */ (function () {
  95302. function QuadraticMatrix(data) {
  95303. this.data = new Array(10);
  95304. for (var i = 0; i < 10; ++i) {
  95305. if (data && data[i]) {
  95306. this.data[i] = data[i];
  95307. }
  95308. else {
  95309. this.data[i] = 0;
  95310. }
  95311. }
  95312. }
  95313. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  95314. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  95315. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  95316. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  95317. return det;
  95318. };
  95319. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  95320. for (var i = 0; i < 10; ++i) {
  95321. this.data[i] += matrix.data[i];
  95322. }
  95323. };
  95324. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  95325. for (var i = 0; i < 10; ++i) {
  95326. this.data[i] += data[i];
  95327. }
  95328. };
  95329. QuadraticMatrix.prototype.add = function (matrix) {
  95330. var m = new QuadraticMatrix();
  95331. for (var i = 0; i < 10; ++i) {
  95332. m.data[i] = this.data[i] + matrix.data[i];
  95333. }
  95334. return m;
  95335. };
  95336. QuadraticMatrix.FromData = function (a, b, c, d) {
  95337. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  95338. };
  95339. //returning an array to avoid garbage collection
  95340. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  95341. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  95342. };
  95343. return QuadraticMatrix;
  95344. }());
  95345. BABYLON.QuadraticMatrix = QuadraticMatrix;
  95346. var Reference = /** @class */ (function () {
  95347. function Reference(vertexId, triangleId) {
  95348. this.vertexId = vertexId;
  95349. this.triangleId = triangleId;
  95350. }
  95351. return Reference;
  95352. }());
  95353. BABYLON.Reference = Reference;
  95354. /**
  95355. * An implementation of the Quadratic Error simplification algorithm.
  95356. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  95357. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  95358. * @author RaananW
  95359. */
  95360. var QuadraticErrorSimplification = /** @class */ (function () {
  95361. function QuadraticErrorSimplification(_mesh) {
  95362. this._mesh = _mesh;
  95363. this.syncIterations = 5000;
  95364. this.aggressiveness = 7;
  95365. this.decimationIterations = 100;
  95366. this.boundingBoxEpsilon = BABYLON.Epsilon;
  95367. }
  95368. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  95369. var _this = this;
  95370. this.initDecimatedMesh();
  95371. //iterating through the submeshes array, one after the other.
  95372. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  95373. _this.initWithMesh(loop.index, function () {
  95374. _this.runDecimation(settings, loop.index, function () {
  95375. loop.executeNext();
  95376. });
  95377. }, settings.optimizeMesh);
  95378. }, function () {
  95379. setTimeout(function () {
  95380. successCallback(_this._reconstructedMesh);
  95381. }, 0);
  95382. });
  95383. };
  95384. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  95385. var _this = this;
  95386. var targetCount = ~~(this.triangles.length * settings.quality);
  95387. var deletedTriangles = 0;
  95388. var triangleCount = this.triangles.length;
  95389. var iterationFunction = function (iteration, callback) {
  95390. setTimeout(function () {
  95391. if (iteration % 5 === 0) {
  95392. _this.updateMesh(iteration === 0);
  95393. }
  95394. for (var i = 0; i < _this.triangles.length; ++i) {
  95395. _this.triangles[i].isDirty = false;
  95396. }
  95397. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  95398. var trianglesIterator = function (i) {
  95399. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  95400. var t = _this.triangles[tIdx];
  95401. if (!t)
  95402. return;
  95403. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  95404. return;
  95405. }
  95406. for (var j = 0; j < 3; ++j) {
  95407. if (t.error[j] < threshold) {
  95408. var deleted0 = [];
  95409. var deleted1 = [];
  95410. var v0 = t.vertices[j];
  95411. var v1 = t.vertices[(j + 1) % 3];
  95412. if (v0.isBorder || v1.isBorder)
  95413. continue;
  95414. var p = BABYLON.Vector3.Zero();
  95415. var n = BABYLON.Vector3.Zero();
  95416. var uv = BABYLON.Vector2.Zero();
  95417. var color = new BABYLON.Color4(0, 0, 0, 1);
  95418. _this.calculateError(v0, v1, p, n, uv, color);
  95419. var delTr = new Array();
  95420. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  95421. continue;
  95422. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  95423. continue;
  95424. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  95425. continue;
  95426. var uniqueArray = new Array();
  95427. delTr.forEach(function (deletedT) {
  95428. if (uniqueArray.indexOf(deletedT) === -1) {
  95429. deletedT.deletePending = true;
  95430. uniqueArray.push(deletedT);
  95431. }
  95432. });
  95433. if (uniqueArray.length % 2 !== 0) {
  95434. continue;
  95435. }
  95436. v0.q = v1.q.add(v0.q);
  95437. v0.updatePosition(p);
  95438. var tStart = _this.references.length;
  95439. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  95440. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  95441. var tCount = _this.references.length - tStart;
  95442. if (tCount <= v0.triangleCount) {
  95443. if (tCount) {
  95444. for (var c = 0; c < tCount; c++) {
  95445. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  95446. }
  95447. }
  95448. }
  95449. else {
  95450. v0.triangleStart = tStart;
  95451. }
  95452. v0.triangleCount = tCount;
  95453. break;
  95454. }
  95455. }
  95456. };
  95457. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  95458. }, 0);
  95459. };
  95460. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  95461. if (triangleCount - deletedTriangles <= targetCount)
  95462. loop.breakLoop();
  95463. else {
  95464. iterationFunction(loop.index, function () {
  95465. loop.executeNext();
  95466. });
  95467. }
  95468. }, function () {
  95469. setTimeout(function () {
  95470. //reconstruct this part of the mesh
  95471. _this.reconstructMesh(submeshIndex);
  95472. successCallback();
  95473. }, 0);
  95474. });
  95475. };
  95476. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  95477. var _this = this;
  95478. this.vertices = [];
  95479. this.triangles = [];
  95480. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95481. var indices = this._mesh.getIndices();
  95482. var submesh = this._mesh.subMeshes[submeshIndex];
  95483. var findInVertices = function (positionToSearch) {
  95484. if (optimizeMesh) {
  95485. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  95486. if (_this.vertices[ii].position.equals(positionToSearch)) {
  95487. return _this.vertices[ii];
  95488. }
  95489. }
  95490. }
  95491. return null;
  95492. };
  95493. var vertexReferences = [];
  95494. var vertexInit = function (i) {
  95495. if (!positionData) {
  95496. return;
  95497. }
  95498. var offset = i + submesh.verticesStart;
  95499. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  95500. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  95501. vertex.originalOffsets.push(offset);
  95502. if (vertex.id === _this.vertices.length) {
  95503. _this.vertices.push(vertex);
  95504. }
  95505. vertexReferences.push(vertex.id);
  95506. };
  95507. //var totalVertices = mesh.getTotalVertices();
  95508. var totalVertices = submesh.verticesCount;
  95509. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  95510. var indicesInit = function (i) {
  95511. if (!indices) {
  95512. return;
  95513. }
  95514. var offset = (submesh.indexStart / 3) + i;
  95515. var pos = (offset * 3);
  95516. var i0 = indices[pos + 0];
  95517. var i1 = indices[pos + 1];
  95518. var i2 = indices[pos + 2];
  95519. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  95520. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  95521. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  95522. var triangle = new DecimationTriangle([v0, v1, v2]);
  95523. triangle.originalOffset = pos;
  95524. _this.triangles.push(triangle);
  95525. };
  95526. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  95527. _this.init(callback);
  95528. });
  95529. });
  95530. };
  95531. QuadraticErrorSimplification.prototype.init = function (callback) {
  95532. var _this = this;
  95533. var triangleInit1 = function (i) {
  95534. var t = _this.triangles[i];
  95535. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  95536. for (var j = 0; j < 3; j++) {
  95537. 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))));
  95538. }
  95539. };
  95540. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  95541. var triangleInit2 = function (i) {
  95542. var t = _this.triangles[i];
  95543. for (var j = 0; j < 3; ++j) {
  95544. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  95545. }
  95546. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95547. };
  95548. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  95549. callback();
  95550. });
  95551. });
  95552. };
  95553. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  95554. var newTriangles = [];
  95555. var i;
  95556. for (i = 0; i < this.vertices.length; ++i) {
  95557. this.vertices[i].triangleCount = 0;
  95558. }
  95559. var t;
  95560. var j;
  95561. for (i = 0; i < this.triangles.length; ++i) {
  95562. if (!this.triangles[i].deleted) {
  95563. t = this.triangles[i];
  95564. for (j = 0; j < 3; ++j) {
  95565. t.vertices[j].triangleCount = 1;
  95566. }
  95567. newTriangles.push(t);
  95568. }
  95569. }
  95570. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  95571. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  95572. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  95573. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  95574. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  95575. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  95576. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  95577. var vertexCount = 0;
  95578. for (i = 0; i < this.vertices.length; ++i) {
  95579. var vertex = this.vertices[i];
  95580. vertex.id = vertexCount;
  95581. if (vertex.triangleCount) {
  95582. vertex.originalOffsets.forEach(function (originalOffset) {
  95583. if (!normalData) {
  95584. return;
  95585. }
  95586. newPositionData.push(vertex.position.x);
  95587. newPositionData.push(vertex.position.y);
  95588. newPositionData.push(vertex.position.z);
  95589. newNormalData.push(normalData[originalOffset * 3]);
  95590. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  95591. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  95592. if (uvs && uvs.length) {
  95593. newUVsData.push(uvs[(originalOffset * 2)]);
  95594. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  95595. }
  95596. else if (colorsData && colorsData.length) {
  95597. newColorsData.push(colorsData[(originalOffset * 4)]);
  95598. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  95599. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  95600. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  95601. }
  95602. ++vertexCount;
  95603. });
  95604. }
  95605. }
  95606. var startingIndex = this._reconstructedMesh.getTotalIndices();
  95607. var startingVertex = this._reconstructedMesh.getTotalVertices();
  95608. var submeshesArray = this._reconstructedMesh.subMeshes;
  95609. this._reconstructedMesh.subMeshes = [];
  95610. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  95611. var originalIndices = this._mesh.getIndices();
  95612. for (i = 0; i < newTriangles.length; ++i) {
  95613. t = newTriangles[i]; //now get the new referencing point for each vertex
  95614. [0, 1, 2].forEach(function (idx) {
  95615. var id = originalIndices[t.originalOffset + idx];
  95616. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  95617. if (offset < 0)
  95618. offset = 0;
  95619. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  95620. });
  95621. }
  95622. //overwriting the old vertex buffers and indices.
  95623. this._reconstructedMesh.setIndices(newIndicesArray);
  95624. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  95625. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  95626. if (newUVsData.length > 0)
  95627. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  95628. if (newColorsData.length > 0)
  95629. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  95630. //create submesh
  95631. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  95632. if (submeshIndex > 0) {
  95633. this._reconstructedMesh.subMeshes = [];
  95634. submeshesArray.forEach(function (submesh) {
  95635. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  95636. });
  95637. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  95638. }
  95639. };
  95640. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  95641. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  95642. this._reconstructedMesh.material = this._mesh.material;
  95643. this._reconstructedMesh.parent = this._mesh.parent;
  95644. this._reconstructedMesh.isVisible = false;
  95645. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  95646. };
  95647. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  95648. for (var i = 0; i < vertex1.triangleCount; ++i) {
  95649. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  95650. if (t.deleted)
  95651. continue;
  95652. var s = this.references[vertex1.triangleStart + i].vertexId;
  95653. var v1 = t.vertices[(s + 1) % 3];
  95654. var v2 = t.vertices[(s + 2) % 3];
  95655. if ((v1 === vertex2 || v2 === vertex2)) {
  95656. deletedArray[i] = true;
  95657. delTr.push(t);
  95658. continue;
  95659. }
  95660. var d1 = v1.position.subtract(point);
  95661. d1 = d1.normalize();
  95662. var d2 = v2.position.subtract(point);
  95663. d2 = d2.normalize();
  95664. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  95665. return true;
  95666. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  95667. deletedArray[i] = false;
  95668. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  95669. return true;
  95670. }
  95671. return false;
  95672. };
  95673. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  95674. var newDeleted = deletedTriangles;
  95675. for (var i = 0; i < vertex.triangleCount; ++i) {
  95676. var ref = this.references[vertex.triangleStart + i];
  95677. var t = this.triangles[ref.triangleId];
  95678. if (t.deleted)
  95679. continue;
  95680. if (deletedArray[i] && t.deletePending) {
  95681. t.deleted = true;
  95682. newDeleted++;
  95683. continue;
  95684. }
  95685. t.vertices[ref.vertexId] = origVertex;
  95686. t.isDirty = true;
  95687. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  95688. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  95689. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  95690. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95691. this.references.push(ref);
  95692. }
  95693. return newDeleted;
  95694. };
  95695. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  95696. for (var i = 0; i < this.vertices.length; ++i) {
  95697. var vCount = [];
  95698. var vId = [];
  95699. var v = this.vertices[i];
  95700. var j;
  95701. for (j = 0; j < v.triangleCount; ++j) {
  95702. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  95703. for (var ii = 0; ii < 3; ii++) {
  95704. var ofs = 0;
  95705. var vv = triangle.vertices[ii];
  95706. while (ofs < vCount.length) {
  95707. if (vId[ofs] === vv.id)
  95708. break;
  95709. ++ofs;
  95710. }
  95711. if (ofs === vCount.length) {
  95712. vCount.push(1);
  95713. vId.push(vv.id);
  95714. }
  95715. else {
  95716. vCount[ofs]++;
  95717. }
  95718. }
  95719. }
  95720. for (j = 0; j < vCount.length; ++j) {
  95721. if (vCount[j] === 1) {
  95722. this.vertices[vId[j]].isBorder = true;
  95723. }
  95724. else {
  95725. this.vertices[vId[j]].isBorder = false;
  95726. }
  95727. }
  95728. }
  95729. };
  95730. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  95731. if (identifyBorders === void 0) { identifyBorders = false; }
  95732. var i;
  95733. if (!identifyBorders) {
  95734. var newTrianglesVector = [];
  95735. for (i = 0; i < this.triangles.length; ++i) {
  95736. if (!this.triangles[i].deleted) {
  95737. newTrianglesVector.push(this.triangles[i]);
  95738. }
  95739. }
  95740. this.triangles = newTrianglesVector;
  95741. }
  95742. for (i = 0; i < this.vertices.length; ++i) {
  95743. this.vertices[i].triangleCount = 0;
  95744. this.vertices[i].triangleStart = 0;
  95745. }
  95746. var t;
  95747. var j;
  95748. var v;
  95749. for (i = 0; i < this.triangles.length; ++i) {
  95750. t = this.triangles[i];
  95751. for (j = 0; j < 3; ++j) {
  95752. v = t.vertices[j];
  95753. v.triangleCount++;
  95754. }
  95755. }
  95756. var tStart = 0;
  95757. for (i = 0; i < this.vertices.length; ++i) {
  95758. this.vertices[i].triangleStart = tStart;
  95759. tStart += this.vertices[i].triangleCount;
  95760. this.vertices[i].triangleCount = 0;
  95761. }
  95762. var newReferences = new Array(this.triangles.length * 3);
  95763. for (i = 0; i < this.triangles.length; ++i) {
  95764. t = this.triangles[i];
  95765. for (j = 0; j < 3; ++j) {
  95766. v = t.vertices[j];
  95767. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  95768. v.triangleCount++;
  95769. }
  95770. }
  95771. this.references = newReferences;
  95772. if (identifyBorders) {
  95773. this.identifyBorder();
  95774. }
  95775. };
  95776. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  95777. var x = point.x;
  95778. var y = point.y;
  95779. var z = point.z;
  95780. 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
  95781. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  95782. };
  95783. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  95784. var q = vertex1.q.add(vertex2.q);
  95785. var border = vertex1.isBorder && vertex2.isBorder;
  95786. var error = 0;
  95787. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  95788. if (qDet !== 0 && !border) {
  95789. if (!pointResult) {
  95790. pointResult = BABYLON.Vector3.Zero();
  95791. }
  95792. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  95793. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  95794. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  95795. error = this.vertexError(q, pointResult);
  95796. }
  95797. else {
  95798. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  95799. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  95800. var error1 = this.vertexError(q, vertex1.position);
  95801. var error2 = this.vertexError(q, vertex2.position);
  95802. var error3 = this.vertexError(q, p3);
  95803. error = Math.min(error1, error2, error3);
  95804. if (error === error1) {
  95805. if (pointResult) {
  95806. pointResult.copyFrom(vertex1.position);
  95807. }
  95808. }
  95809. else if (error === error2) {
  95810. if (pointResult) {
  95811. pointResult.copyFrom(vertex2.position);
  95812. }
  95813. }
  95814. else {
  95815. if (pointResult) {
  95816. pointResult.copyFrom(p3);
  95817. }
  95818. }
  95819. }
  95820. return error;
  95821. };
  95822. return QuadraticErrorSimplification;
  95823. }());
  95824. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95825. })(BABYLON || (BABYLON = {}));
  95826. //# sourceMappingURL=babylon.meshSimplification.js.map
  95827. var BABYLON;
  95828. (function (BABYLON) {
  95829. var MeshLODLevel = /** @class */ (function () {
  95830. function MeshLODLevel(distance, mesh) {
  95831. this.distance = distance;
  95832. this.mesh = mesh;
  95833. }
  95834. return MeshLODLevel;
  95835. }());
  95836. BABYLON.MeshLODLevel = MeshLODLevel;
  95837. })(BABYLON || (BABYLON = {}));
  95838. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95839. var BABYLON;
  95840. (function (BABYLON) {
  95841. /**
  95842. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95843. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95844. */
  95845. var SceneOptimization = /** @class */ (function () {
  95846. /**
  95847. * Creates the SceneOptimization object
  95848. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95849. * @param desc defines the description associated with the optimization
  95850. */
  95851. function SceneOptimization(
  95852. /**
  95853. * Defines the priority of this optimization (0 by default which means first in the list)
  95854. */
  95855. priority) {
  95856. if (priority === void 0) { priority = 0; }
  95857. this.priority = priority;
  95858. }
  95859. /**
  95860. * Gets a string describing the action executed by the current optimization
  95861. * @returns description string
  95862. */
  95863. SceneOptimization.prototype.getDescription = function () {
  95864. return "";
  95865. };
  95866. /**
  95867. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95868. * @param scene defines the current scene where to apply this optimization
  95869. * @param optimizer defines the current optimizer
  95870. * @returns true if everything that can be done was applied
  95871. */
  95872. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95873. return true;
  95874. };
  95875. ;
  95876. return SceneOptimization;
  95877. }());
  95878. BABYLON.SceneOptimization = SceneOptimization;
  95879. /**
  95880. * Defines an optimization used to reduce the size of render target textures
  95881. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95882. */
  95883. var TextureOptimization = /** @class */ (function (_super) {
  95884. __extends(TextureOptimization, _super);
  95885. /**
  95886. * Creates the TextureOptimization object
  95887. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95888. * @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
  95889. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95890. */
  95891. function TextureOptimization(
  95892. /**
  95893. * Defines the priority of this optimization (0 by default which means first in the list)
  95894. */
  95895. priority,
  95896. /**
  95897. * 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
  95898. */
  95899. maximumSize,
  95900. /**
  95901. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95902. */
  95903. step) {
  95904. if (priority === void 0) { priority = 0; }
  95905. if (maximumSize === void 0) { maximumSize = 1024; }
  95906. if (step === void 0) { step = 0.5; }
  95907. var _this = _super.call(this, priority) || this;
  95908. _this.priority = priority;
  95909. _this.maximumSize = maximumSize;
  95910. _this.step = step;
  95911. return _this;
  95912. }
  95913. /**
  95914. * Gets a string describing the action executed by the current optimization
  95915. * @returns description string
  95916. */
  95917. TextureOptimization.prototype.getDescription = function () {
  95918. return "Reducing render target texture size to " + this.maximumSize;
  95919. };
  95920. /**
  95921. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95922. * @param scene defines the current scene where to apply this optimization
  95923. * @param optimizer defines the current optimizer
  95924. * @returns true if everything that can be done was applied
  95925. */
  95926. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95927. var allDone = true;
  95928. for (var index = 0; index < scene.textures.length; index++) {
  95929. var texture = scene.textures[index];
  95930. if (!texture.canRescale || texture.getContext) {
  95931. continue;
  95932. }
  95933. var currentSize = texture.getSize();
  95934. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95935. if (maxDimension > this.maximumSize) {
  95936. texture.scale(this.step);
  95937. allDone = false;
  95938. }
  95939. }
  95940. return allDone;
  95941. };
  95942. return TextureOptimization;
  95943. }(SceneOptimization));
  95944. BABYLON.TextureOptimization = TextureOptimization;
  95945. /**
  95946. * Defines an optimization used to increase or decrease the rendering resolution
  95947. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95948. */
  95949. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95950. __extends(HardwareScalingOptimization, _super);
  95951. /**
  95952. * Creates the HardwareScalingOptimization object
  95953. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95954. * @param maximumScale defines the maximum scale to use (2 by default)
  95955. * @param step defines the step to use between two passes (0.5 by default)
  95956. */
  95957. function HardwareScalingOptimization(
  95958. /**
  95959. * Defines the priority of this optimization (0 by default which means first in the list)
  95960. */
  95961. priority,
  95962. /**
  95963. * Defines the maximum scale to use (2 by default)
  95964. */
  95965. maximumScale,
  95966. /**
  95967. * Defines the step to use between two passes (0.5 by default)
  95968. */
  95969. step) {
  95970. if (priority === void 0) { priority = 0; }
  95971. if (maximumScale === void 0) { maximumScale = 2; }
  95972. if (step === void 0) { step = 0.25; }
  95973. var _this = _super.call(this, priority) || this;
  95974. _this.priority = priority;
  95975. _this.maximumScale = maximumScale;
  95976. _this.step = step;
  95977. _this._currentScale = -1;
  95978. _this._directionOffset = 1;
  95979. return _this;
  95980. }
  95981. /**
  95982. * Gets a string describing the action executed by the current optimization
  95983. * @return description string
  95984. */
  95985. HardwareScalingOptimization.prototype.getDescription = function () {
  95986. return "Setting hardware scaling level to " + this._currentScale;
  95987. };
  95988. /**
  95989. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95990. * @param scene defines the current scene where to apply this optimization
  95991. * @param optimizer defines the current optimizer
  95992. * @returns true if everything that can be done was applied
  95993. */
  95994. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95995. if (this._currentScale === -1) {
  95996. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95997. if (this._currentScale > this.maximumScale) {
  95998. this._directionOffset = -1;
  95999. }
  96000. }
  96001. this._currentScale += this._directionOffset * this.step;
  96002. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  96003. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  96004. };
  96005. ;
  96006. return HardwareScalingOptimization;
  96007. }(SceneOptimization));
  96008. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  96009. /**
  96010. * Defines an optimization used to remove shadows
  96011. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96012. */
  96013. var ShadowsOptimization = /** @class */ (function (_super) {
  96014. __extends(ShadowsOptimization, _super);
  96015. function ShadowsOptimization() {
  96016. return _super !== null && _super.apply(this, arguments) || this;
  96017. }
  96018. /**
  96019. * Gets a string describing the action executed by the current optimization
  96020. * @return description string
  96021. */
  96022. ShadowsOptimization.prototype.getDescription = function () {
  96023. return "Turning shadows on/off";
  96024. };
  96025. /**
  96026. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96027. * @param scene defines the current scene where to apply this optimization
  96028. * @param optimizer defines the current optimizer
  96029. * @returns true if everything that can be done was applied
  96030. */
  96031. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  96032. scene.shadowsEnabled = optimizer.isInImprovementMode;
  96033. return true;
  96034. };
  96035. ;
  96036. return ShadowsOptimization;
  96037. }(SceneOptimization));
  96038. BABYLON.ShadowsOptimization = ShadowsOptimization;
  96039. /**
  96040. * Defines an optimization used to turn post-processes off
  96041. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96042. */
  96043. var PostProcessesOptimization = /** @class */ (function (_super) {
  96044. __extends(PostProcessesOptimization, _super);
  96045. function PostProcessesOptimization() {
  96046. return _super !== null && _super.apply(this, arguments) || this;
  96047. }
  96048. /**
  96049. * Gets a string describing the action executed by the current optimization
  96050. * @return description string
  96051. */
  96052. PostProcessesOptimization.prototype.getDescription = function () {
  96053. return "Turning post-processes on/off";
  96054. };
  96055. /**
  96056. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96057. * @param scene defines the current scene where to apply this optimization
  96058. * @param optimizer defines the current optimizer
  96059. * @returns true if everything that can be done was applied
  96060. */
  96061. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  96062. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  96063. return true;
  96064. };
  96065. ;
  96066. return PostProcessesOptimization;
  96067. }(SceneOptimization));
  96068. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  96069. /**
  96070. * Defines an optimization used to turn lens flares off
  96071. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96072. */
  96073. var LensFlaresOptimization = /** @class */ (function (_super) {
  96074. __extends(LensFlaresOptimization, _super);
  96075. function LensFlaresOptimization() {
  96076. return _super !== null && _super.apply(this, arguments) || this;
  96077. }
  96078. /**
  96079. * Gets a string describing the action executed by the current optimization
  96080. * @return description string
  96081. */
  96082. LensFlaresOptimization.prototype.getDescription = function () {
  96083. return "Turning lens flares on/off";
  96084. };
  96085. /**
  96086. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96087. * @param scene defines the current scene where to apply this optimization
  96088. * @param optimizer defines the current optimizer
  96089. * @returns true if everything that can be done was applied
  96090. */
  96091. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  96092. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  96093. return true;
  96094. };
  96095. ;
  96096. return LensFlaresOptimization;
  96097. }(SceneOptimization));
  96098. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  96099. /**
  96100. * Defines an optimization based on user defined callback.
  96101. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96102. */
  96103. var CustomOptimization = /** @class */ (function (_super) {
  96104. __extends(CustomOptimization, _super);
  96105. function CustomOptimization() {
  96106. return _super !== null && _super.apply(this, arguments) || this;
  96107. }
  96108. /**
  96109. * Gets a string describing the action executed by the current optimization
  96110. * @returns description string
  96111. */
  96112. CustomOptimization.prototype.getDescription = function () {
  96113. if (this.onGetDescription) {
  96114. return this.onGetDescription();
  96115. }
  96116. return "Running user defined callback";
  96117. };
  96118. /**
  96119. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96120. * @param scene defines the current scene where to apply this optimization
  96121. * @param optimizer defines the current optimizer
  96122. * @returns true if everything that can be done was applied
  96123. */
  96124. CustomOptimization.prototype.apply = function (scene, optimizer) {
  96125. if (this.onApply) {
  96126. return this.onApply(scene, optimizer);
  96127. }
  96128. return true;
  96129. };
  96130. ;
  96131. return CustomOptimization;
  96132. }(SceneOptimization));
  96133. BABYLON.CustomOptimization = CustomOptimization;
  96134. /**
  96135. * Defines an optimization used to turn particles off
  96136. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96137. */
  96138. var ParticlesOptimization = /** @class */ (function (_super) {
  96139. __extends(ParticlesOptimization, _super);
  96140. function ParticlesOptimization() {
  96141. return _super !== null && _super.apply(this, arguments) || this;
  96142. }
  96143. /**
  96144. * Gets a string describing the action executed by the current optimization
  96145. * @return description string
  96146. */
  96147. ParticlesOptimization.prototype.getDescription = function () {
  96148. return "Turning particles on/off";
  96149. };
  96150. /**
  96151. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96152. * @param scene defines the current scene where to apply this optimization
  96153. * @param optimizer defines the current optimizer
  96154. * @returns true if everything that can be done was applied
  96155. */
  96156. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  96157. scene.particlesEnabled = optimizer.isInImprovementMode;
  96158. return true;
  96159. };
  96160. ;
  96161. return ParticlesOptimization;
  96162. }(SceneOptimization));
  96163. BABYLON.ParticlesOptimization = ParticlesOptimization;
  96164. /**
  96165. * Defines an optimization used to turn render targets off
  96166. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96167. */
  96168. var RenderTargetsOptimization = /** @class */ (function (_super) {
  96169. __extends(RenderTargetsOptimization, _super);
  96170. function RenderTargetsOptimization() {
  96171. return _super !== null && _super.apply(this, arguments) || this;
  96172. }
  96173. /**
  96174. * Gets a string describing the action executed by the current optimization
  96175. * @return description string
  96176. */
  96177. RenderTargetsOptimization.prototype.getDescription = function () {
  96178. return "Turning render targets off";
  96179. };
  96180. /**
  96181. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96182. * @param scene defines the current scene where to apply this optimization
  96183. * @param optimizer defines the current optimizer
  96184. * @returns true if everything that can be done was applied
  96185. */
  96186. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  96187. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  96188. return true;
  96189. };
  96190. ;
  96191. return RenderTargetsOptimization;
  96192. }(SceneOptimization));
  96193. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  96194. /**
  96195. * Defines an optimization used to merge meshes with compatible materials
  96196. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96197. */
  96198. var MergeMeshesOptimization = /** @class */ (function (_super) {
  96199. __extends(MergeMeshesOptimization, _super);
  96200. function MergeMeshesOptimization() {
  96201. var _this = _super !== null && _super.apply(this, arguments) || this;
  96202. _this._canBeMerged = function (abstractMesh) {
  96203. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  96204. return false;
  96205. }
  96206. var mesh = abstractMesh;
  96207. if (mesh.isDisposed()) {
  96208. return false;
  96209. }
  96210. if (!mesh.isVisible || !mesh.isEnabled()) {
  96211. return false;
  96212. }
  96213. if (mesh.instances.length > 0) {
  96214. return false;
  96215. }
  96216. if (mesh.skeleton || mesh.hasLODLevels) {
  96217. return false;
  96218. }
  96219. return true;
  96220. };
  96221. return _this;
  96222. }
  96223. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  96224. /**
  96225. * Gets or sets a boolean which defines if optimization octree has to be updated
  96226. */
  96227. get: function () {
  96228. return MergeMeshesOptimization._UpdateSelectionTree;
  96229. },
  96230. /**
  96231. * Gets or sets a boolean which defines if optimization octree has to be updated
  96232. */
  96233. set: function (value) {
  96234. MergeMeshesOptimization._UpdateSelectionTree = value;
  96235. },
  96236. enumerable: true,
  96237. configurable: true
  96238. });
  96239. /**
  96240. * Gets a string describing the action executed by the current optimization
  96241. * @return description string
  96242. */
  96243. MergeMeshesOptimization.prototype.getDescription = function () {
  96244. return "Merging similar meshes together";
  96245. };
  96246. /**
  96247. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96248. * @param scene defines the current scene where to apply this optimization
  96249. * @param optimizer defines the current optimizer
  96250. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  96251. * @returns true if everything that can be done was applied
  96252. */
  96253. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  96254. var globalPool = scene.meshes.slice(0);
  96255. var globalLength = globalPool.length;
  96256. for (var index = 0; index < globalLength; index++) {
  96257. var currentPool = new Array();
  96258. var current = globalPool[index];
  96259. // Checks
  96260. if (!this._canBeMerged(current)) {
  96261. continue;
  96262. }
  96263. currentPool.push(current);
  96264. // Find compatible meshes
  96265. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  96266. var otherMesh = globalPool[subIndex];
  96267. if (!this._canBeMerged(otherMesh)) {
  96268. continue;
  96269. }
  96270. if (otherMesh.material !== current.material) {
  96271. continue;
  96272. }
  96273. if (otherMesh.checkCollisions !== current.checkCollisions) {
  96274. continue;
  96275. }
  96276. currentPool.push(otherMesh);
  96277. globalLength--;
  96278. globalPool.splice(subIndex, 1);
  96279. subIndex--;
  96280. }
  96281. if (currentPool.length < 2) {
  96282. continue;
  96283. }
  96284. // Merge meshes
  96285. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  96286. }
  96287. if (updateSelectionTree != undefined) {
  96288. if (updateSelectionTree) {
  96289. scene.createOrUpdateSelectionOctree();
  96290. }
  96291. }
  96292. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  96293. scene.createOrUpdateSelectionOctree();
  96294. }
  96295. return true;
  96296. };
  96297. ;
  96298. MergeMeshesOptimization._UpdateSelectionTree = false;
  96299. return MergeMeshesOptimization;
  96300. }(SceneOptimization));
  96301. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  96302. /**
  96303. * Defines a list of options used by SceneOptimizer
  96304. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96305. */
  96306. var SceneOptimizerOptions = /** @class */ (function () {
  96307. /**
  96308. * Creates a new list of options used by SceneOptimizer
  96309. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  96310. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  96311. */
  96312. function SceneOptimizerOptions(
  96313. /**
  96314. * Defines the target frame rate to reach (60 by default)
  96315. */
  96316. targetFrameRate,
  96317. /**
  96318. * Defines the interval between two checkes (2000ms by default)
  96319. */
  96320. trackerDuration) {
  96321. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  96322. if (trackerDuration === void 0) { trackerDuration = 2000; }
  96323. this.targetFrameRate = targetFrameRate;
  96324. this.trackerDuration = trackerDuration;
  96325. /**
  96326. * Gets the list of optimizations to apply
  96327. */
  96328. this.optimizations = new Array();
  96329. }
  96330. /**
  96331. * Add a new optimization
  96332. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  96333. * @returns the current SceneOptimizerOptions
  96334. */
  96335. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  96336. this.optimizations.push(optimization);
  96337. return this;
  96338. };
  96339. /**
  96340. * Add a new custom optimization
  96341. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  96342. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  96343. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96344. * @returns the current SceneOptimizerOptions
  96345. */
  96346. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  96347. if (priority === void 0) { priority = 0; }
  96348. var optimization = new CustomOptimization(priority);
  96349. optimization.onApply = onApply;
  96350. optimization.onGetDescription = onGetDescription;
  96351. this.optimizations.push(optimization);
  96352. return this;
  96353. };
  96354. /**
  96355. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  96356. * @param targetFrameRate defines the target frame rate (60 by default)
  96357. * @returns a SceneOptimizerOptions object
  96358. */
  96359. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  96360. var result = new SceneOptimizerOptions(targetFrameRate);
  96361. var priority = 0;
  96362. result.addOptimization(new MergeMeshesOptimization(priority));
  96363. result.addOptimization(new ShadowsOptimization(priority));
  96364. result.addOptimization(new LensFlaresOptimization(priority));
  96365. // Next priority
  96366. priority++;
  96367. result.addOptimization(new PostProcessesOptimization(priority));
  96368. result.addOptimization(new ParticlesOptimization(priority));
  96369. // Next priority
  96370. priority++;
  96371. result.addOptimization(new TextureOptimization(priority, 1024));
  96372. return result;
  96373. };
  96374. /**
  96375. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  96376. * @param targetFrameRate defines the target frame rate (60 by default)
  96377. * @returns a SceneOptimizerOptions object
  96378. */
  96379. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  96380. var result = new SceneOptimizerOptions(targetFrameRate);
  96381. var priority = 0;
  96382. result.addOptimization(new MergeMeshesOptimization(priority));
  96383. result.addOptimization(new ShadowsOptimization(priority));
  96384. result.addOptimization(new LensFlaresOptimization(priority));
  96385. // Next priority
  96386. priority++;
  96387. result.addOptimization(new PostProcessesOptimization(priority));
  96388. result.addOptimization(new ParticlesOptimization(priority));
  96389. // Next priority
  96390. priority++;
  96391. result.addOptimization(new TextureOptimization(priority, 512));
  96392. // Next priority
  96393. priority++;
  96394. result.addOptimization(new RenderTargetsOptimization(priority));
  96395. // Next priority
  96396. priority++;
  96397. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  96398. return result;
  96399. };
  96400. /**
  96401. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  96402. * @param targetFrameRate defines the target frame rate (60 by default)
  96403. * @returns a SceneOptimizerOptions object
  96404. */
  96405. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  96406. var result = new SceneOptimizerOptions(targetFrameRate);
  96407. var priority = 0;
  96408. result.addOptimization(new MergeMeshesOptimization(priority));
  96409. result.addOptimization(new ShadowsOptimization(priority));
  96410. result.addOptimization(new LensFlaresOptimization(priority));
  96411. // Next priority
  96412. priority++;
  96413. result.addOptimization(new PostProcessesOptimization(priority));
  96414. result.addOptimization(new ParticlesOptimization(priority));
  96415. // Next priority
  96416. priority++;
  96417. result.addOptimization(new TextureOptimization(priority, 256));
  96418. // Next priority
  96419. priority++;
  96420. result.addOptimization(new RenderTargetsOptimization(priority));
  96421. // Next priority
  96422. priority++;
  96423. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  96424. return result;
  96425. };
  96426. return SceneOptimizerOptions;
  96427. }());
  96428. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  96429. /**
  96430. * Class used to run optimizations in order to reach a target frame rate
  96431. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96432. */
  96433. var SceneOptimizer = /** @class */ (function () {
  96434. /**
  96435. * Creates a new SceneOptimizer
  96436. * @param scene defines the scene to work on
  96437. * @param options defines the options to use with the SceneOptimizer
  96438. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  96439. * @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)
  96440. */
  96441. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  96442. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  96443. if (improvementMode === void 0) { improvementMode = false; }
  96444. var _this = this;
  96445. this._isRunning = false;
  96446. this._currentPriorityLevel = 0;
  96447. this._targetFrameRate = 60;
  96448. this._trackerDuration = 2000;
  96449. this._currentFrameRate = 0;
  96450. this._improvementMode = false;
  96451. /**
  96452. * Defines an observable called when the optimizer reaches the target frame rate
  96453. */
  96454. this.onSuccessObservable = new BABYLON.Observable();
  96455. /**
  96456. * Defines an observable called when the optimizer enables an optimization
  96457. */
  96458. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  96459. /**
  96460. * Defines an observable called when the optimizer is not able to reach the target frame rate
  96461. */
  96462. this.onFailureObservable = new BABYLON.Observable();
  96463. if (!options) {
  96464. this._options = new SceneOptimizerOptions();
  96465. }
  96466. else {
  96467. this._options = options;
  96468. }
  96469. if (this._options.targetFrameRate) {
  96470. this._targetFrameRate = this._options.targetFrameRate;
  96471. }
  96472. if (this._options.trackerDuration) {
  96473. this._trackerDuration = this._options.trackerDuration;
  96474. }
  96475. if (autoGeneratePriorities) {
  96476. var priority = 0;
  96477. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  96478. var optim = _a[_i];
  96479. optim.priority = priority++;
  96480. }
  96481. }
  96482. this._improvementMode = improvementMode;
  96483. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96484. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  96485. _this._sceneDisposeObserver = null;
  96486. _this.dispose();
  96487. });
  96488. }
  96489. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  96490. /**
  96491. * Gets a boolean indicating if the optimizer is in improvement mode
  96492. */
  96493. get: function () {
  96494. return this._improvementMode;
  96495. },
  96496. enumerable: true,
  96497. configurable: true
  96498. });
  96499. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  96500. /**
  96501. * Gets the current priority level (0 at start)
  96502. */
  96503. get: function () {
  96504. return this._currentPriorityLevel;
  96505. },
  96506. enumerable: true,
  96507. configurable: true
  96508. });
  96509. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  96510. /**
  96511. * Gets the current frame rate checked by the SceneOptimizer
  96512. */
  96513. get: function () {
  96514. return this._currentFrameRate;
  96515. },
  96516. enumerable: true,
  96517. configurable: true
  96518. });
  96519. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  96520. /**
  96521. * Gets or sets the current target frame rate (60 by default)
  96522. */
  96523. get: function () {
  96524. return this._targetFrameRate;
  96525. },
  96526. /**
  96527. * Gets or sets the current target frame rate (60 by default)
  96528. */
  96529. set: function (value) {
  96530. this._targetFrameRate = value;
  96531. },
  96532. enumerable: true,
  96533. configurable: true
  96534. });
  96535. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  96536. /**
  96537. * Gets or sets the current interval between two checks (every 2000ms by default)
  96538. */
  96539. get: function () {
  96540. return this._trackerDuration;
  96541. },
  96542. /**
  96543. * Gets or sets the current interval between two checks (every 2000ms by default)
  96544. */
  96545. set: function (value) {
  96546. this._trackerDuration = value;
  96547. },
  96548. enumerable: true,
  96549. configurable: true
  96550. });
  96551. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  96552. /**
  96553. * Gets the list of active optimizations
  96554. */
  96555. get: function () {
  96556. return this._options.optimizations;
  96557. },
  96558. enumerable: true,
  96559. configurable: true
  96560. });
  96561. /**
  96562. * Stops the current optimizer
  96563. */
  96564. SceneOptimizer.prototype.stop = function () {
  96565. this._isRunning = false;
  96566. };
  96567. /**
  96568. * Reset the optimizer to initial step (current priority level = 0)
  96569. */
  96570. SceneOptimizer.prototype.reset = function () {
  96571. this._currentPriorityLevel = 0;
  96572. };
  96573. /**
  96574. * Start the optimizer. By default it will try to reach a specific framerate
  96575. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  96576. */
  96577. SceneOptimizer.prototype.start = function () {
  96578. var _this = this;
  96579. if (this._isRunning) {
  96580. return;
  96581. }
  96582. this._isRunning = true;
  96583. // Let's wait for the scene to be ready before running our check
  96584. this._scene.executeWhenReady(function () {
  96585. setTimeout(function () {
  96586. _this._checkCurrentState();
  96587. }, _this._trackerDuration);
  96588. });
  96589. };
  96590. SceneOptimizer.prototype._checkCurrentState = function () {
  96591. var _this = this;
  96592. if (!this._isRunning) {
  96593. return;
  96594. }
  96595. var scene = this._scene;
  96596. var options = this._options;
  96597. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  96598. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  96599. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  96600. this._isRunning = false;
  96601. this.onSuccessObservable.notifyObservers(this);
  96602. return;
  96603. }
  96604. // Apply current level of optimizations
  96605. var allDone = true;
  96606. var noOptimizationApplied = true;
  96607. for (var index = 0; index < options.optimizations.length; index++) {
  96608. var optimization = options.optimizations[index];
  96609. if (optimization.priority === this._currentPriorityLevel) {
  96610. noOptimizationApplied = false;
  96611. allDone = allDone && optimization.apply(scene, this);
  96612. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  96613. }
  96614. }
  96615. // If no optimization was applied, this is a failure :(
  96616. if (noOptimizationApplied) {
  96617. this._isRunning = false;
  96618. this.onFailureObservable.notifyObservers(this);
  96619. return;
  96620. }
  96621. // If all optimizations were done, move to next level
  96622. if (allDone) {
  96623. this._currentPriorityLevel++;
  96624. }
  96625. // Let's the system running for a specific amount of time before checking FPS
  96626. scene.executeWhenReady(function () {
  96627. setTimeout(function () {
  96628. _this._checkCurrentState();
  96629. }, _this._trackerDuration);
  96630. });
  96631. };
  96632. /**
  96633. * Release all resources
  96634. */
  96635. SceneOptimizer.prototype.dispose = function () {
  96636. this.stop();
  96637. this.onSuccessObservable.clear();
  96638. this.onFailureObservable.clear();
  96639. this.onNewOptimizationAppliedObservable.clear();
  96640. if (this._sceneDisposeObserver) {
  96641. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96642. }
  96643. };
  96644. /**
  96645. * Helper function to create a SceneOptimizer with one single line of code
  96646. * @param scene defines the scene to work on
  96647. * @param options defines the options to use with the SceneOptimizer
  96648. * @param onSuccess defines a callback to call on success
  96649. * @param onFailure defines a callback to call on failure
  96650. * @returns the new SceneOptimizer object
  96651. */
  96652. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  96653. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  96654. if (onSuccess) {
  96655. optimizer.onSuccessObservable.add(function () {
  96656. onSuccess();
  96657. });
  96658. }
  96659. if (onFailure) {
  96660. optimizer.onFailureObservable.add(function () {
  96661. onFailure();
  96662. });
  96663. }
  96664. optimizer.start();
  96665. return optimizer;
  96666. };
  96667. return SceneOptimizer;
  96668. }());
  96669. BABYLON.SceneOptimizer = SceneOptimizer;
  96670. })(BABYLON || (BABYLON = {}));
  96671. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  96672. var BABYLON;
  96673. (function (BABYLON) {
  96674. var OutlineRenderer = /** @class */ (function () {
  96675. function OutlineRenderer(scene) {
  96676. this.zOffset = 1;
  96677. this._scene = scene;
  96678. }
  96679. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  96680. var _this = this;
  96681. if (useOverlay === void 0) { useOverlay = false; }
  96682. var scene = this._scene;
  96683. var engine = this._scene.getEngine();
  96684. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96685. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  96686. return;
  96687. }
  96688. var mesh = subMesh.getRenderingMesh();
  96689. var material = subMesh.getMaterial();
  96690. if (!material || !scene.activeCamera) {
  96691. return;
  96692. }
  96693. engine.enableEffect(this._effect);
  96694. // Logarithmic depth
  96695. if (material.useLogarithmicDepth) {
  96696. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  96697. }
  96698. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  96699. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  96700. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  96701. // Bones
  96702. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96703. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96704. }
  96705. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  96706. // Alpha test
  96707. if (material && material.needAlphaTesting()) {
  96708. var alphaTexture = material.getAlphaTestTexture();
  96709. if (alphaTexture) {
  96710. this._effect.setTexture("diffuseSampler", alphaTexture);
  96711. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  96712. }
  96713. }
  96714. engine.setZOffset(-this.zOffset);
  96715. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  96716. engine.setZOffset(0);
  96717. };
  96718. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  96719. var defines = [];
  96720. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  96721. var mesh = subMesh.getMesh();
  96722. var material = subMesh.getMaterial();
  96723. if (material) {
  96724. // Alpha test
  96725. if (material.needAlphaTesting()) {
  96726. defines.push("#define ALPHATEST");
  96727. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96728. attribs.push(BABYLON.VertexBuffer.UVKind);
  96729. defines.push("#define UV1");
  96730. }
  96731. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  96732. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96733. defines.push("#define UV2");
  96734. }
  96735. }
  96736. //Logarithmic depth
  96737. if (material.useLogarithmicDepth) {
  96738. defines.push("#define LOGARITHMICDEPTH");
  96739. }
  96740. }
  96741. // Bones
  96742. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96745. if (mesh.numBoneInfluencers > 4) {
  96746. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96747. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96748. }
  96749. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96750. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  96751. }
  96752. else {
  96753. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96754. }
  96755. // Instances
  96756. if (useInstances) {
  96757. defines.push("#define INSTANCES");
  96758. attribs.push("world0");
  96759. attribs.push("world1");
  96760. attribs.push("world2");
  96761. attribs.push("world3");
  96762. }
  96763. // Get correct effect
  96764. var join = defines.join("\n");
  96765. if (this._cachedDefines !== join) {
  96766. this._cachedDefines = join;
  96767. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  96768. }
  96769. return this._effect.isReady();
  96770. };
  96771. return OutlineRenderer;
  96772. }());
  96773. BABYLON.OutlineRenderer = OutlineRenderer;
  96774. })(BABYLON || (BABYLON = {}));
  96775. //# sourceMappingURL=babylon.outlineRenderer.js.map
  96776. var BABYLON;
  96777. (function (BABYLON) {
  96778. var FaceAdjacencies = /** @class */ (function () {
  96779. function FaceAdjacencies() {
  96780. this.edges = new Array();
  96781. this.edgesConnectedCount = 0;
  96782. }
  96783. return FaceAdjacencies;
  96784. }());
  96785. var EdgesRenderer = /** @class */ (function () {
  96786. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  96787. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  96788. if (epsilon === void 0) { epsilon = 0.95; }
  96789. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  96790. this.edgesWidthScalerForOrthographic = 1000.0;
  96791. this.edgesWidthScalerForPerspective = 50.0;
  96792. this._linesPositions = new Array();
  96793. this._linesNormals = new Array();
  96794. this._linesIndices = new Array();
  96795. this._buffers = {};
  96796. this._checkVerticesInsteadOfIndices = false;
  96797. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  96798. this.isEnabled = true;
  96799. this._source = source;
  96800. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  96801. this._epsilon = epsilon;
  96802. this._prepareRessources();
  96803. this._generateEdgesLines();
  96804. }
  96805. EdgesRenderer.prototype._prepareRessources = function () {
  96806. if (this._lineShader) {
  96807. return;
  96808. }
  96809. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  96810. attributes: ["position", "normal"],
  96811. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96812. });
  96813. this._lineShader.disableDepthWrite = true;
  96814. this._lineShader.backFaceCulling = false;
  96815. };
  96816. EdgesRenderer.prototype._rebuild = function () {
  96817. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96818. if (buffer) {
  96819. buffer._rebuild();
  96820. }
  96821. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96822. if (buffer) {
  96823. buffer._rebuild();
  96824. }
  96825. var scene = this._source.getScene();
  96826. var engine = scene.getEngine();
  96827. this._ib = engine.createIndexBuffer(this._linesIndices);
  96828. };
  96829. EdgesRenderer.prototype.dispose = function () {
  96830. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96831. if (buffer) {
  96832. buffer.dispose();
  96833. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96834. }
  96835. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96836. if (buffer) {
  96837. buffer.dispose();
  96838. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96839. }
  96840. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96841. this._lineShader.dispose();
  96842. };
  96843. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96844. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96845. return 0;
  96846. }
  96847. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96848. return 1;
  96849. }
  96850. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96851. return 2;
  96852. }
  96853. return -1;
  96854. };
  96855. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96856. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96857. return 0;
  96858. }
  96859. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96860. return 1;
  96861. }
  96862. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96863. return 2;
  96864. }
  96865. return -1;
  96866. };
  96867. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96868. var needToCreateLine;
  96869. if (edge === undefined) {
  96870. needToCreateLine = true;
  96871. }
  96872. else {
  96873. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96874. needToCreateLine = dotProduct < this._epsilon;
  96875. }
  96876. if (needToCreateLine) {
  96877. var offset = this._linesPositions.length / 3;
  96878. var normal = p0.subtract(p1);
  96879. normal.normalize();
  96880. // Positions
  96881. this._linesPositions.push(p0.x);
  96882. this._linesPositions.push(p0.y);
  96883. this._linesPositions.push(p0.z);
  96884. this._linesPositions.push(p0.x);
  96885. this._linesPositions.push(p0.y);
  96886. this._linesPositions.push(p0.z);
  96887. this._linesPositions.push(p1.x);
  96888. this._linesPositions.push(p1.y);
  96889. this._linesPositions.push(p1.z);
  96890. this._linesPositions.push(p1.x);
  96891. this._linesPositions.push(p1.y);
  96892. this._linesPositions.push(p1.z);
  96893. // Normals
  96894. this._linesNormals.push(p1.x);
  96895. this._linesNormals.push(p1.y);
  96896. this._linesNormals.push(p1.z);
  96897. this._linesNormals.push(-1);
  96898. this._linesNormals.push(p1.x);
  96899. this._linesNormals.push(p1.y);
  96900. this._linesNormals.push(p1.z);
  96901. this._linesNormals.push(1);
  96902. this._linesNormals.push(p0.x);
  96903. this._linesNormals.push(p0.y);
  96904. this._linesNormals.push(p0.z);
  96905. this._linesNormals.push(-1);
  96906. this._linesNormals.push(p0.x);
  96907. this._linesNormals.push(p0.y);
  96908. this._linesNormals.push(p0.z);
  96909. this._linesNormals.push(1);
  96910. // Indices
  96911. this._linesIndices.push(offset);
  96912. this._linesIndices.push(offset + 1);
  96913. this._linesIndices.push(offset + 2);
  96914. this._linesIndices.push(offset);
  96915. this._linesIndices.push(offset + 2);
  96916. this._linesIndices.push(offset + 3);
  96917. }
  96918. };
  96919. EdgesRenderer.prototype._generateEdgesLines = function () {
  96920. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96921. var indices = this._source.getIndices();
  96922. if (!indices || !positions) {
  96923. return;
  96924. }
  96925. // First let's find adjacencies
  96926. var adjacencies = new Array();
  96927. var faceNormals = new Array();
  96928. var index;
  96929. var faceAdjacencies;
  96930. // Prepare faces
  96931. for (index = 0; index < indices.length; index += 3) {
  96932. faceAdjacencies = new FaceAdjacencies();
  96933. var p0Index = indices[index];
  96934. var p1Index = indices[index + 1];
  96935. var p2Index = indices[index + 2];
  96936. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96937. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96938. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96939. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96940. faceNormal.normalize();
  96941. faceNormals.push(faceNormal);
  96942. adjacencies.push(faceAdjacencies);
  96943. }
  96944. // Scan
  96945. for (index = 0; index < adjacencies.length; index++) {
  96946. faceAdjacencies = adjacencies[index];
  96947. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96948. var otherFaceAdjacencies = adjacencies[otherIndex];
  96949. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96950. break;
  96951. }
  96952. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96953. continue;
  96954. }
  96955. var otherP0 = indices[otherIndex * 3];
  96956. var otherP1 = indices[otherIndex * 3 + 1];
  96957. var otherP2 = indices[otherIndex * 3 + 2];
  96958. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96959. var otherEdgeIndex = 0;
  96960. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96961. continue;
  96962. }
  96963. switch (edgeIndex) {
  96964. case 0:
  96965. if (this._checkVerticesInsteadOfIndices) {
  96966. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96967. }
  96968. else {
  96969. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96970. }
  96971. break;
  96972. case 1:
  96973. if (this._checkVerticesInsteadOfIndices) {
  96974. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96975. }
  96976. else {
  96977. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96978. }
  96979. break;
  96980. case 2:
  96981. if (this._checkVerticesInsteadOfIndices) {
  96982. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96983. }
  96984. else {
  96985. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96986. }
  96987. break;
  96988. }
  96989. if (otherEdgeIndex === -1) {
  96990. continue;
  96991. }
  96992. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96993. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96994. faceAdjacencies.edgesConnectedCount++;
  96995. otherFaceAdjacencies.edgesConnectedCount++;
  96996. if (faceAdjacencies.edgesConnectedCount === 3) {
  96997. break;
  96998. }
  96999. }
  97000. }
  97001. }
  97002. // Create lines
  97003. for (index = 0; index < adjacencies.length; index++) {
  97004. // 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
  97005. var current = adjacencies[index];
  97006. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  97007. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  97008. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  97009. }
  97010. // Merge into a single mesh
  97011. var engine = this._source.getScene().getEngine();
  97012. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  97013. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  97014. this._ib = engine.createIndexBuffer(this._linesIndices);
  97015. this._indicesCount = this._linesIndices.length;
  97016. };
  97017. EdgesRenderer.prototype.render = function () {
  97018. var scene = this._source.getScene();
  97019. if (!this._lineShader.isReady() || !scene.activeCamera) {
  97020. return;
  97021. }
  97022. var engine = scene.getEngine();
  97023. this._lineShader._preBind();
  97024. // VBOs
  97025. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  97026. scene.resetCachedMaterial();
  97027. this._lineShader.setColor4("color", this._source.edgesColor);
  97028. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  97029. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  97030. }
  97031. else {
  97032. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  97033. }
  97034. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  97035. this._lineShader.bind(this._source.getWorldMatrix());
  97036. // Draw order
  97037. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  97038. this._lineShader.unbind();
  97039. engine.setDepthWrite(true);
  97040. };
  97041. return EdgesRenderer;
  97042. }());
  97043. BABYLON.EdgesRenderer = EdgesRenderer;
  97044. })(BABYLON || (BABYLON = {}));
  97045. //# sourceMappingURL=babylon.edgesRenderer.js.map
  97046. var BABYLON;
  97047. (function (BABYLON) {
  97048. // Adds the parser to the scene parsers.
  97049. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  97050. if (parsedData.effectLayers) {
  97051. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  97052. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  97053. container.effectLayers.push(effectLayer);
  97054. }
  97055. }
  97056. });
  97057. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  97058. var index = this.effectLayers.indexOf(toRemove);
  97059. if (index !== -1) {
  97060. this.effectLayers.splice(index, 1);
  97061. }
  97062. return index;
  97063. };
  97064. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  97065. this.effectLayers.push(newEffectLayer);
  97066. };
  97067. /**
  97068. * Defines the layer scene component responsible to manage any effect layers
  97069. * in a given scene.
  97070. */
  97071. var EffectLayerSceneComponent = /** @class */ (function () {
  97072. /**
  97073. * Creates a new instance of the component for the given scene
  97074. * @param scene Defines the scene to register the component in
  97075. */
  97076. function EffectLayerSceneComponent(scene) {
  97077. /**
  97078. * The component name helpfull to identify the component in the list of scene components.
  97079. */
  97080. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  97081. this._renderEffects = false;
  97082. this._needStencil = false;
  97083. this._previousStencilState = false;
  97084. this.scene = scene;
  97085. this._engine = scene.getEngine();
  97086. scene.effectLayers = new Array();
  97087. }
  97088. /**
  97089. * Registers the component in a given scene
  97090. */
  97091. EffectLayerSceneComponent.prototype.register = function () {
  97092. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  97093. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  97094. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  97095. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  97096. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  97097. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  97098. };
  97099. /**
  97100. * Rebuilds the elements related to this component in case of
  97101. * context lost for instance.
  97102. */
  97103. EffectLayerSceneComponent.prototype.rebuild = function () {
  97104. var layers = this.scene.effectLayers;
  97105. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  97106. var effectLayer = layers_1[_i];
  97107. effectLayer._rebuild();
  97108. }
  97109. };
  97110. /**
  97111. * Serializes the component data to the specified json object
  97112. * @param serializationObject The object to serialize to
  97113. */
  97114. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  97115. // Effect layers
  97116. serializationObject.effectLayers = [];
  97117. var layers = this.scene.effectLayers;
  97118. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  97119. var effectLayer = layers_2[_i];
  97120. if (effectLayer.serialize) {
  97121. serializationObject.effectLayers.push(effectLayer.serialize());
  97122. }
  97123. }
  97124. };
  97125. /**
  97126. * Adds all the element from the container to the scene
  97127. * @param container the container holding the elements
  97128. */
  97129. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  97130. var _this = this;
  97131. if (!container.effectLayers) {
  97132. return;
  97133. }
  97134. container.effectLayers.forEach(function (o) {
  97135. _this.scene.addEffectLayer(o);
  97136. });
  97137. };
  97138. /**
  97139. * Removes all the elements in the container from the scene
  97140. * @param container contains the elements to remove
  97141. */
  97142. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  97143. var _this = this;
  97144. if (!container.effectLayers) {
  97145. return;
  97146. }
  97147. container.effectLayers.forEach(function (o) {
  97148. _this.scene.removeEffectLayer(o);
  97149. });
  97150. };
  97151. /**
  97152. * Disposes the component and the associated ressources.
  97153. */
  97154. EffectLayerSceneComponent.prototype.dispose = function () {
  97155. var layers = this.scene.effectLayers;
  97156. while (layers.length) {
  97157. layers[0].dispose();
  97158. }
  97159. };
  97160. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  97161. var layers = this.scene.effectLayers;
  97162. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  97163. var layer = layers_3[_i];
  97164. if (!layer.hasMesh(mesh)) {
  97165. continue;
  97166. }
  97167. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  97168. var subMesh = _b[_a];
  97169. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  97170. return false;
  97171. }
  97172. }
  97173. }
  97174. return true;
  97175. };
  97176. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  97177. this._renderEffects = false;
  97178. this._needStencil = false;
  97179. var layers = this.scene.effectLayers;
  97180. if (layers && layers.length > 0) {
  97181. this._previousStencilState = this._engine.getStencilBuffer();
  97182. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  97183. var effectLayer = layers_4[_i];
  97184. if (effectLayer.shouldRender() &&
  97185. (!effectLayer.camera ||
  97186. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  97187. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  97188. this._renderEffects = true;
  97189. this._needStencil = this._needStencil || effectLayer.needStencil();
  97190. var renderTarget = effectLayer._mainTexture;
  97191. if (renderTarget._shouldRender()) {
  97192. this.scene.incrementRenderId();
  97193. renderTarget.render(false, false);
  97194. }
  97195. }
  97196. }
  97197. this.scene.incrementRenderId();
  97198. }
  97199. };
  97200. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  97201. // Activate effect Layer stencil
  97202. if (this._needStencil) {
  97203. this._engine.setStencilBuffer(true);
  97204. }
  97205. };
  97206. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  97207. // Restore effect Layer stencil
  97208. if (this._needStencil) {
  97209. this._engine.setStencilBuffer(this._previousStencilState);
  97210. }
  97211. };
  97212. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  97213. if (this._renderEffects) {
  97214. this._engine.setDepthBuffer(false);
  97215. var layers = this.scene.effectLayers;
  97216. for (var i = 0; i < layers.length; i++) {
  97217. var effectLayer = layers[i];
  97218. if (effectLayer.renderingGroupId === renderingGroupId) {
  97219. if (effectLayer.shouldRender()) {
  97220. effectLayer.render();
  97221. }
  97222. }
  97223. }
  97224. this._engine.setDepthBuffer(true);
  97225. }
  97226. };
  97227. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  97228. if (this._renderEffects) {
  97229. this._draw(-1);
  97230. }
  97231. };
  97232. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  97233. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  97234. this._draw(index);
  97235. }
  97236. };
  97237. return EffectLayerSceneComponent;
  97238. }());
  97239. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  97240. })(BABYLON || (BABYLON = {}));
  97241. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  97242. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97243. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97244. s = arguments[i];
  97245. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97246. t[p] = s[p];
  97247. }
  97248. return t;
  97249. };
  97250. var BABYLON;
  97251. (function (BABYLON) {
  97252. /**
  97253. * The effect layer Helps adding post process effect blended with the main pass.
  97254. *
  97255. * This can be for instance use to generate glow or higlight effects on the scene.
  97256. *
  97257. * The effect layer class can not be used directly and is intented to inherited from to be
  97258. * customized per effects.
  97259. */
  97260. var EffectLayer = /** @class */ (function () {
  97261. /**
  97262. * Instantiates a new effect Layer and references it in the scene.
  97263. * @param name The name of the layer
  97264. * @param scene The scene to use the layer in
  97265. */
  97266. function EffectLayer(
  97267. /** The Friendly of the effect in the scene */
  97268. name, scene) {
  97269. this._vertexBuffers = {};
  97270. this._maxSize = 0;
  97271. this._mainTextureDesiredSize = { width: 0, height: 0 };
  97272. this._shouldRender = true;
  97273. this._postProcesses = [];
  97274. this._textures = [];
  97275. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  97276. /**
  97277. * The clear color of the texture used to generate the glow map.
  97278. */
  97279. this.neutralColor = new BABYLON.Color4();
  97280. /**
  97281. * Specifies wether the highlight layer is enabled or not.
  97282. */
  97283. this.isEnabled = true;
  97284. /**
  97285. * An event triggered when the effect layer has been disposed.
  97286. */
  97287. this.onDisposeObservable = new BABYLON.Observable();
  97288. /**
  97289. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  97290. */
  97291. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  97292. /**
  97293. * An event triggered when the generated texture is being merged in the scene.
  97294. */
  97295. this.onBeforeComposeObservable = new BABYLON.Observable();
  97296. /**
  97297. * An event triggered when the generated texture has been merged in the scene.
  97298. */
  97299. this.onAfterComposeObservable = new BABYLON.Observable();
  97300. /**
  97301. * An event triggered when the efffect layer changes its size.
  97302. */
  97303. this.onSizeChangedObservable = new BABYLON.Observable();
  97304. this.name = name;
  97305. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97306. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  97307. if (!component) {
  97308. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  97309. this._scene._addComponent(component);
  97310. }
  97311. this._engine = this._scene.getEngine();
  97312. this._maxSize = this._engine.getCaps().maxTextureSize;
  97313. this._scene.effectLayers.push(this);
  97314. // Generate Buffers
  97315. this._generateIndexBuffer();
  97316. this._genrateVertexBuffer();
  97317. }
  97318. Object.defineProperty(EffectLayer.prototype, "camera", {
  97319. /**
  97320. * Gets the camera attached to the layer.
  97321. */
  97322. get: function () {
  97323. return this._effectLayerOptions.camera;
  97324. },
  97325. enumerable: true,
  97326. configurable: true
  97327. });
  97328. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  97329. /**
  97330. * Gets the rendering group id the layer should render in.
  97331. */
  97332. get: function () {
  97333. return this._effectLayerOptions.renderingGroupId;
  97334. },
  97335. enumerable: true,
  97336. configurable: true
  97337. });
  97338. /**
  97339. * Initializes the effect layer with the required options.
  97340. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  97341. */
  97342. EffectLayer.prototype._init = function (options) {
  97343. // Adapt options
  97344. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97345. this._setMainTextureSize();
  97346. this._createMainTexture();
  97347. this._createTextureAndPostProcesses();
  97348. this._mergeEffect = this._createMergeEffect();
  97349. };
  97350. /**
  97351. * Generates the index buffer of the full screen quad blending to the main canvas.
  97352. */
  97353. EffectLayer.prototype._generateIndexBuffer = function () {
  97354. // Indices
  97355. var indices = [];
  97356. indices.push(0);
  97357. indices.push(1);
  97358. indices.push(2);
  97359. indices.push(0);
  97360. indices.push(2);
  97361. indices.push(3);
  97362. this._indexBuffer = this._engine.createIndexBuffer(indices);
  97363. };
  97364. /**
  97365. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  97366. */
  97367. EffectLayer.prototype._genrateVertexBuffer = function () {
  97368. // VBO
  97369. var vertices = [];
  97370. vertices.push(1, 1);
  97371. vertices.push(-1, 1);
  97372. vertices.push(-1, -1);
  97373. vertices.push(1, -1);
  97374. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97375. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97376. };
  97377. /**
  97378. * Sets the main texture desired size which is the closest power of two
  97379. * of the engine canvas size.
  97380. */
  97381. EffectLayer.prototype._setMainTextureSize = function () {
  97382. if (this._effectLayerOptions.mainTextureFixedSize) {
  97383. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  97384. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  97385. }
  97386. else {
  97387. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  97388. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  97389. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  97390. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  97391. }
  97392. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  97393. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  97394. };
  97395. /**
  97396. * Creates the main texture for the effect layer.
  97397. */
  97398. EffectLayer.prototype._createMainTexture = function () {
  97399. var _this = this;
  97400. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  97401. width: this._mainTextureDesiredSize.width,
  97402. height: this._mainTextureDesiredSize.height
  97403. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97404. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  97405. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97406. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97407. this._mainTexture.anisotropicFilteringLevel = 1;
  97408. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97409. this._mainTexture.renderParticles = false;
  97410. this._mainTexture.renderList = null;
  97411. this._mainTexture.ignoreCameraViewport = true;
  97412. // Custom render function
  97413. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  97414. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  97415. var index;
  97416. var engine = _this._scene.getEngine();
  97417. if (depthOnlySubMeshes.length) {
  97418. engine.setColorWrite(false);
  97419. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  97420. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  97421. }
  97422. engine.setColorWrite(true);
  97423. }
  97424. for (index = 0; index < opaqueSubMeshes.length; index++) {
  97425. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  97426. }
  97427. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  97428. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  97429. }
  97430. for (index = 0; index < transparentSubMeshes.length; index++) {
  97431. _this._renderSubMesh(transparentSubMeshes.data[index]);
  97432. }
  97433. };
  97434. this._mainTexture.onClearObservable.add(function (engine) {
  97435. engine.clear(_this.neutralColor, true, true, true);
  97436. });
  97437. };
  97438. /**
  97439. * Checks for the readiness of the element composing the layer.
  97440. * @param subMesh the mesh to check for
  97441. * @param useInstances specify wether or not to use instances to render the mesh
  97442. * @param emissiveTexture the associated emissive texture used to generate the glow
  97443. * @return true if ready otherwise, false
  97444. */
  97445. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  97446. var material = subMesh.getMaterial();
  97447. if (!material) {
  97448. return false;
  97449. }
  97450. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  97451. return false;
  97452. }
  97453. var defines = [];
  97454. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97455. var mesh = subMesh.getMesh();
  97456. var uv1 = false;
  97457. var uv2 = false;
  97458. // Alpha test
  97459. if (material && material.needAlphaTesting()) {
  97460. var alphaTexture = material.getAlphaTestTexture();
  97461. if (alphaTexture) {
  97462. defines.push("#define ALPHATEST");
  97463. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97464. alphaTexture.coordinatesIndex === 1) {
  97465. defines.push("#define DIFFUSEUV2");
  97466. uv2 = true;
  97467. }
  97468. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97469. defines.push("#define DIFFUSEUV1");
  97470. uv1 = true;
  97471. }
  97472. }
  97473. }
  97474. // Emissive
  97475. if (emissiveTexture) {
  97476. defines.push("#define EMISSIVE");
  97477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97478. emissiveTexture.coordinatesIndex === 1) {
  97479. defines.push("#define EMISSIVEUV2");
  97480. uv2 = true;
  97481. }
  97482. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97483. defines.push("#define EMISSIVEUV1");
  97484. uv1 = true;
  97485. }
  97486. }
  97487. if (uv1) {
  97488. attribs.push(BABYLON.VertexBuffer.UVKind);
  97489. defines.push("#define UV1");
  97490. }
  97491. if (uv2) {
  97492. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97493. defines.push("#define UV2");
  97494. }
  97495. // Bones
  97496. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  97497. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  97498. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  97499. if (mesh.numBoneInfluencers > 4) {
  97500. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  97501. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  97502. }
  97503. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  97504. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  97505. }
  97506. else {
  97507. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97508. }
  97509. // Morph targets
  97510. var manager = mesh.morphTargetManager;
  97511. var morphInfluencers = 0;
  97512. if (manager) {
  97513. if (manager.numInfluencers > 0) {
  97514. defines.push("#define MORPHTARGETS");
  97515. morphInfluencers = manager.numInfluencers;
  97516. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  97517. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  97518. }
  97519. }
  97520. // Instances
  97521. if (useInstances) {
  97522. defines.push("#define INSTANCES");
  97523. attribs.push("world0");
  97524. attribs.push("world1");
  97525. attribs.push("world2");
  97526. attribs.push("world3");
  97527. }
  97528. // Get correct effect
  97529. var join = defines.join("\n");
  97530. if (this._cachedDefines !== join) {
  97531. this._cachedDefines = join;
  97532. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  97533. }
  97534. return this._effectLayerMapGenerationEffect.isReady();
  97535. };
  97536. /**
  97537. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  97538. */
  97539. EffectLayer.prototype.render = function () {
  97540. var currentEffect = this._mergeEffect;
  97541. // Check
  97542. if (!currentEffect.isReady())
  97543. return;
  97544. for (var i = 0; i < this._postProcesses.length; i++) {
  97545. if (!this._postProcesses[i].isReady()) {
  97546. return;
  97547. }
  97548. }
  97549. var engine = this._scene.getEngine();
  97550. this.onBeforeComposeObservable.notifyObservers(this);
  97551. // Render
  97552. engine.enableEffect(currentEffect);
  97553. engine.setState(false);
  97554. // VBOs
  97555. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97556. // Cache
  97557. var previousAlphaMode = engine.getAlphaMode();
  97558. // Go Blend.
  97559. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  97560. // Blends the map on the main canvas.
  97561. this._internalRender(currentEffect);
  97562. // Restore Alpha
  97563. engine.setAlphaMode(previousAlphaMode);
  97564. this.onAfterComposeObservable.notifyObservers(this);
  97565. // Handle size changes.
  97566. var size = this._mainTexture.getSize();
  97567. this._setMainTextureSize();
  97568. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  97569. // Recreate RTT and post processes on size change.
  97570. this.onSizeChangedObservable.notifyObservers(this);
  97571. this._disposeTextureAndPostProcesses();
  97572. this._createMainTexture();
  97573. this._createTextureAndPostProcesses();
  97574. }
  97575. };
  97576. /**
  97577. * Determine if a given mesh will be used in the current effect.
  97578. * @param mesh mesh to test
  97579. * @returns true if the mesh will be used
  97580. */
  97581. EffectLayer.prototype.hasMesh = function (mesh) {
  97582. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  97583. return true;
  97584. }
  97585. return false;
  97586. };
  97587. /**
  97588. * Returns true if the layer contains information to display, otherwise false.
  97589. * @returns true if the glow layer should be rendered
  97590. */
  97591. EffectLayer.prototype.shouldRender = function () {
  97592. return this.isEnabled && this._shouldRender;
  97593. };
  97594. /**
  97595. * Returns true if the mesh should render, otherwise false.
  97596. * @param mesh The mesh to render
  97597. * @returns true if it should render otherwise false
  97598. */
  97599. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  97600. return true;
  97601. };
  97602. /**
  97603. * Returns true if the mesh should render, otherwise false.
  97604. * @param mesh The mesh to render
  97605. * @returns true if it should render otherwise false
  97606. */
  97607. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  97608. return true;
  97609. };
  97610. /**
  97611. * Renders the submesh passed in parameter to the generation map.
  97612. */
  97613. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  97614. var _this = this;
  97615. if (!this.shouldRender()) {
  97616. return;
  97617. }
  97618. var material = subMesh.getMaterial();
  97619. var mesh = subMesh.getRenderingMesh();
  97620. var scene = this._scene;
  97621. var engine = scene.getEngine();
  97622. if (!material) {
  97623. return;
  97624. }
  97625. // Do not block in blend mode.
  97626. if (material.needAlphaBlendingForMesh(mesh)) {
  97627. return;
  97628. }
  97629. // Culling
  97630. engine.setState(material.backFaceCulling);
  97631. // Managing instances
  97632. var batch = mesh._getInstancesRenderList(subMesh._id);
  97633. if (batch.mustReturn) {
  97634. return;
  97635. }
  97636. // Early Exit per mesh
  97637. if (!this._shouldRenderMesh(mesh)) {
  97638. return;
  97639. }
  97640. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97641. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  97642. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  97643. engine.enableEffect(this._effectLayerMapGenerationEffect);
  97644. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  97645. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  97646. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  97647. // Alpha test
  97648. if (material && material.needAlphaTesting()) {
  97649. var alphaTexture = material.getAlphaTestTexture();
  97650. if (alphaTexture) {
  97651. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  97652. var textureMatrix = alphaTexture.getTextureMatrix();
  97653. if (textureMatrix) {
  97654. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  97655. }
  97656. }
  97657. }
  97658. // Glow emissive only
  97659. if (this._emissiveTextureAndColor.texture) {
  97660. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  97661. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  97662. }
  97663. // Bones
  97664. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97665. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97666. }
  97667. // Morph targets
  97668. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  97669. // Draw
  97670. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  97671. }
  97672. else {
  97673. // Need to reset refresh rate of the main map
  97674. this._mainTexture.resetRefreshCounter();
  97675. }
  97676. };
  97677. /**
  97678. * Rebuild the required buffers.
  97679. * @hidden Internal use only.
  97680. */
  97681. EffectLayer.prototype._rebuild = function () {
  97682. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97683. if (vb) {
  97684. vb._rebuild();
  97685. }
  97686. this._generateIndexBuffer();
  97687. };
  97688. /**
  97689. * Dispose only the render target textures and post process.
  97690. */
  97691. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  97692. this._mainTexture.dispose();
  97693. for (var i = 0; i < this._postProcesses.length; i++) {
  97694. if (this._postProcesses[i]) {
  97695. this._postProcesses[i].dispose();
  97696. }
  97697. }
  97698. this._postProcesses = [];
  97699. for (var i = 0; i < this._textures.length; i++) {
  97700. if (this._textures[i]) {
  97701. this._textures[i].dispose();
  97702. }
  97703. }
  97704. this._textures = [];
  97705. };
  97706. /**
  97707. * Dispose the highlight layer and free resources.
  97708. */
  97709. EffectLayer.prototype.dispose = function () {
  97710. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97711. if (vertexBuffer) {
  97712. vertexBuffer.dispose();
  97713. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97714. }
  97715. if (this._indexBuffer) {
  97716. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97717. this._indexBuffer = null;
  97718. }
  97719. // Clean textures and post processes
  97720. this._disposeTextureAndPostProcesses();
  97721. // Remove from scene
  97722. var index = this._scene.effectLayers.indexOf(this, 0);
  97723. if (index > -1) {
  97724. this._scene.effectLayers.splice(index, 1);
  97725. }
  97726. // Callback
  97727. this.onDisposeObservable.notifyObservers(this);
  97728. this.onDisposeObservable.clear();
  97729. this.onBeforeRenderMainTextureObservable.clear();
  97730. this.onBeforeComposeObservable.clear();
  97731. this.onAfterComposeObservable.clear();
  97732. this.onSizeChangedObservable.clear();
  97733. };
  97734. /**
  97735. * Gets the class name of the effect layer
  97736. * @returns the string with the class name of the effect layer
  97737. */
  97738. EffectLayer.prototype.getClassName = function () {
  97739. return "EffectLayer";
  97740. };
  97741. /**
  97742. * Creates an effect layer from parsed effect layer data
  97743. * @param parsedEffectLayer defines effect layer data
  97744. * @param scene defines the current scene
  97745. * @param rootUrl defines the root URL containing the effect layer information
  97746. * @returns a parsed effect Layer
  97747. */
  97748. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  97749. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  97750. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  97751. };
  97752. __decorate([
  97753. BABYLON.serialize()
  97754. ], EffectLayer.prototype, "name", void 0);
  97755. __decorate([
  97756. BABYLON.serializeAsColor4()
  97757. ], EffectLayer.prototype, "neutralColor", void 0);
  97758. __decorate([
  97759. BABYLON.serialize()
  97760. ], EffectLayer.prototype, "isEnabled", void 0);
  97761. __decorate([
  97762. BABYLON.serializeAsCameraReference()
  97763. ], EffectLayer.prototype, "camera", null);
  97764. __decorate([
  97765. BABYLON.serialize()
  97766. ], EffectLayer.prototype, "renderingGroupId", null);
  97767. return EffectLayer;
  97768. }());
  97769. BABYLON.EffectLayer = EffectLayer;
  97770. })(BABYLON || (BABYLON = {}));
  97771. //# sourceMappingURL=babylon.effectLayer.js.map
  97772. var BABYLON;
  97773. (function (BABYLON) {
  97774. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  97775. for (var index = 0; index < this.effectLayers.length; index++) {
  97776. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  97777. return this.effectLayers[index];
  97778. }
  97779. }
  97780. return null;
  97781. };
  97782. /**
  97783. * Special Glow Blur post process only blurring the alpha channel
  97784. * It enforces keeping the most luminous color in the color channel.
  97785. */
  97786. var GlowBlurPostProcess = /** @class */ (function (_super) {
  97787. __extends(GlowBlurPostProcess, _super);
  97788. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  97789. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  97790. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  97791. _this.direction = direction;
  97792. _this.kernel = kernel;
  97793. _this.onApplyObservable.add(function (effect) {
  97794. effect.setFloat2("screenSize", _this.width, _this.height);
  97795. effect.setVector2("direction", _this.direction);
  97796. effect.setFloat("blurWidth", _this.kernel);
  97797. });
  97798. return _this;
  97799. }
  97800. return GlowBlurPostProcess;
  97801. }(BABYLON.PostProcess));
  97802. /**
  97803. * The highlight layer Helps adding a glow effect around a mesh.
  97804. *
  97805. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97806. * glowy meshes to your scene.
  97807. *
  97808. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  97809. */
  97810. var HighlightLayer = /** @class */ (function (_super) {
  97811. __extends(HighlightLayer, _super);
  97812. /**
  97813. * Instantiates a new highlight Layer and references it to the scene..
  97814. * @param name The name of the layer
  97815. * @param scene The scene to use the layer in
  97816. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97817. */
  97818. function HighlightLayer(name, scene, options) {
  97819. var _this = _super.call(this, name, scene) || this;
  97820. _this.name = name;
  97821. /**
  97822. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97823. */
  97824. _this.innerGlow = true;
  97825. /**
  97826. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97827. */
  97828. _this.outerGlow = true;
  97829. /**
  97830. * An event triggered when the highlight layer is being blurred.
  97831. */
  97832. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97833. /**
  97834. * An event triggered when the highlight layer has been blurred.
  97835. */
  97836. _this.onAfterBlurObservable = new BABYLON.Observable();
  97837. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97838. _this._meshes = {};
  97839. _this._excludedMeshes = {};
  97840. _this.neutralColor = HighlightLayer.NeutralColor;
  97841. // Warn on stencil
  97842. if (!_this._engine.isStencilEnable) {
  97843. 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 }");
  97844. }
  97845. // Adapt options
  97846. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97847. // Initialize the layer
  97848. _this._init({
  97849. alphaBlendingMode: _this._options.alphaBlendingMode,
  97850. camera: _this._options.camera,
  97851. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97852. mainTextureRatio: _this._options.mainTextureRatio,
  97853. renderingGroupId: _this._options.renderingGroupId
  97854. });
  97855. // Do not render as long as no meshes have been added
  97856. _this._shouldRender = false;
  97857. return _this;
  97858. }
  97859. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97860. /**
  97861. * Gets the horizontal size of the blur.
  97862. */
  97863. get: function () {
  97864. return this._horizontalBlurPostprocess.kernel;
  97865. },
  97866. /**
  97867. * Specifies the horizontal size of the blur.
  97868. */
  97869. set: function (value) {
  97870. this._horizontalBlurPostprocess.kernel = value;
  97871. },
  97872. enumerable: true,
  97873. configurable: true
  97874. });
  97875. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97876. /**
  97877. * Gets the vertical size of the blur.
  97878. */
  97879. get: function () {
  97880. return this._verticalBlurPostprocess.kernel;
  97881. },
  97882. /**
  97883. * Specifies the vertical size of the blur.
  97884. */
  97885. set: function (value) {
  97886. this._verticalBlurPostprocess.kernel = value;
  97887. },
  97888. enumerable: true,
  97889. configurable: true
  97890. });
  97891. /**
  97892. * Get the effect name of the layer.
  97893. * @return The effect name
  97894. */
  97895. HighlightLayer.prototype.getEffectName = function () {
  97896. return HighlightLayer.EffectName;
  97897. };
  97898. /**
  97899. * Create the merge effect. This is the shader use to blit the information back
  97900. * to the main canvas at the end of the scene rendering.
  97901. */
  97902. HighlightLayer.prototype._createMergeEffect = function () {
  97903. // Effect
  97904. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97905. };
  97906. /**
  97907. * Creates the render target textures and post processes used in the highlight layer.
  97908. */
  97909. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97910. var _this = this;
  97911. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97912. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97913. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97914. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97915. var textureType = 0;
  97916. if (this._engine.getCaps().textureHalfFloatRender) {
  97917. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97918. }
  97919. else {
  97920. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97921. }
  97922. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97923. width: blurTextureWidth,
  97924. height: blurTextureHeight
  97925. }, this._scene, false, true, textureType);
  97926. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97927. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97928. this._blurTexture.anisotropicFilteringLevel = 16;
  97929. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97930. this._blurTexture.renderParticles = false;
  97931. this._blurTexture.ignoreCameraViewport = true;
  97932. this._textures = [this._blurTexture];
  97933. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97934. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97935. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97936. effect.setTexture("textureSampler", _this._mainTexture);
  97937. });
  97938. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97939. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97940. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97941. });
  97942. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97943. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97944. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97945. });
  97946. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97947. }
  97948. else {
  97949. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97950. width: blurTextureWidth,
  97951. height: blurTextureHeight
  97952. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97953. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97954. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97955. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97956. effect.setTexture("textureSampler", _this._mainTexture);
  97957. });
  97958. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97959. width: blurTextureWidth,
  97960. height: blurTextureHeight
  97961. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97962. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97963. }
  97964. this._mainTexture.onAfterUnbindObservable.add(function () {
  97965. _this.onBeforeBlurObservable.notifyObservers(_this);
  97966. var internalTexture = _this._blurTexture.getInternalTexture();
  97967. if (internalTexture) {
  97968. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97969. }
  97970. _this.onAfterBlurObservable.notifyObservers(_this);
  97971. });
  97972. // Prevent autoClear.
  97973. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97974. };
  97975. /**
  97976. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97977. */
  97978. HighlightLayer.prototype.needStencil = function () {
  97979. return true;
  97980. };
  97981. /**
  97982. * Checks for the readiness of the element composing the layer.
  97983. * @param subMesh the mesh to check for
  97984. * @param useInstances specify wether or not to use instances to render the mesh
  97985. * @param emissiveTexture the associated emissive texture used to generate the glow
  97986. * @return true if ready otherwise, false
  97987. */
  97988. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97989. var material = subMesh.getMaterial();
  97990. var mesh = subMesh.getRenderingMesh();
  97991. if (!material || !mesh || !this._meshes) {
  97992. return false;
  97993. }
  97994. var emissiveTexture = null;
  97995. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97996. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97997. emissiveTexture = material.emissiveTexture;
  97998. }
  97999. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98000. };
  98001. /**
  98002. * Implementation specific of rendering the generating effect on the main canvas.
  98003. * @param effect The effect used to render through
  98004. */
  98005. HighlightLayer.prototype._internalRender = function (effect) {
  98006. // Texture
  98007. effect.setTexture("textureSampler", this._blurTexture);
  98008. // Cache
  98009. var engine = this._engine;
  98010. var previousStencilBuffer = engine.getStencilBuffer();
  98011. var previousStencilFunction = engine.getStencilFunction();
  98012. var previousStencilMask = engine.getStencilMask();
  98013. var previousStencilOperationPass = engine.getStencilOperationPass();
  98014. var previousStencilOperationFail = engine.getStencilOperationFail();
  98015. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  98016. var previousStencilReference = engine.getStencilFunctionReference();
  98017. // Stencil operations
  98018. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  98019. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  98020. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  98021. // Draw order
  98022. engine.setStencilMask(0x00);
  98023. engine.setStencilBuffer(true);
  98024. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  98025. // 2 passes inner outer
  98026. if (this.outerGlow) {
  98027. effect.setFloat("offset", 0);
  98028. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  98029. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98030. }
  98031. if (this.innerGlow) {
  98032. effect.setFloat("offset", 1);
  98033. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  98034. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98035. }
  98036. // Restore Cache
  98037. engine.setStencilFunction(previousStencilFunction);
  98038. engine.setStencilMask(previousStencilMask);
  98039. engine.setStencilBuffer(previousStencilBuffer);
  98040. engine.setStencilOperationPass(previousStencilOperationPass);
  98041. engine.setStencilOperationFail(previousStencilOperationFail);
  98042. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  98043. engine.setStencilFunctionReference(previousStencilReference);
  98044. };
  98045. /**
  98046. * Returns true if the layer contains information to display, otherwise false.
  98047. */
  98048. HighlightLayer.prototype.shouldRender = function () {
  98049. if (_super.prototype.shouldRender.call(this)) {
  98050. return this._meshes ? true : false;
  98051. }
  98052. return false;
  98053. };
  98054. /**
  98055. * Returns true if the mesh should render, otherwise false.
  98056. * @param mesh The mesh to render
  98057. * @returns true if it should render otherwise false
  98058. */
  98059. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  98060. // Excluded Mesh
  98061. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  98062. return false;
  98063. }
  98064. ;
  98065. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98066. return false;
  98067. }
  98068. return true;
  98069. };
  98070. /**
  98071. * Sets the required values for both the emissive texture and and the main color.
  98072. */
  98073. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98074. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98075. if (highlightLayerMesh) {
  98076. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  98077. }
  98078. else {
  98079. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98080. }
  98081. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98082. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98083. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  98084. }
  98085. else {
  98086. this._emissiveTextureAndColor.texture = null;
  98087. }
  98088. };
  98089. /**
  98090. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  98091. * @param mesh The mesh to exclude from the highlight layer
  98092. */
  98093. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  98094. if (!this._excludedMeshes) {
  98095. return;
  98096. }
  98097. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98098. if (!meshExcluded) {
  98099. this._excludedMeshes[mesh.uniqueId] = {
  98100. mesh: mesh,
  98101. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  98102. mesh.getEngine().setStencilBuffer(false);
  98103. }),
  98104. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  98105. mesh.getEngine().setStencilBuffer(true);
  98106. }),
  98107. };
  98108. }
  98109. };
  98110. /**
  98111. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  98112. * @param mesh The mesh to highlight
  98113. */
  98114. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  98115. if (!this._excludedMeshes) {
  98116. return;
  98117. }
  98118. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98119. if (meshExcluded) {
  98120. if (meshExcluded.beforeRender) {
  98121. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  98122. }
  98123. if (meshExcluded.afterRender) {
  98124. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  98125. }
  98126. }
  98127. this._excludedMeshes[mesh.uniqueId] = null;
  98128. };
  98129. /**
  98130. * Determine if a given mesh will be highlighted by the current HighlightLayer
  98131. * @param mesh mesh to test
  98132. * @returns true if the mesh will be highlighted by the current HighlightLayer
  98133. */
  98134. HighlightLayer.prototype.hasMesh = function (mesh) {
  98135. if (!this._meshes) {
  98136. return false;
  98137. }
  98138. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98139. return false;
  98140. }
  98141. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  98142. };
  98143. /**
  98144. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  98145. * @param mesh The mesh to highlight
  98146. * @param color The color of the highlight
  98147. * @param glowEmissiveOnly Extract the glow from the emissive texture
  98148. */
  98149. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  98150. var _this = this;
  98151. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  98152. if (!this._meshes) {
  98153. return;
  98154. }
  98155. var meshHighlight = this._meshes[mesh.uniqueId];
  98156. if (meshHighlight) {
  98157. meshHighlight.color = color;
  98158. }
  98159. else {
  98160. this._meshes[mesh.uniqueId] = {
  98161. mesh: mesh,
  98162. color: color,
  98163. // Lambda required for capture due to Observable this context
  98164. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  98165. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  98166. _this._defaultStencilReference(mesh);
  98167. }
  98168. else {
  98169. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  98170. }
  98171. }),
  98172. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  98173. glowEmissiveOnly: glowEmissiveOnly
  98174. };
  98175. mesh.onDisposeObservable.add(function () {
  98176. _this._disposeMesh(mesh);
  98177. });
  98178. }
  98179. this._shouldRender = true;
  98180. };
  98181. /**
  98182. * Remove a mesh from the highlight layer in order to make it stop glowing.
  98183. * @param mesh The mesh to highlight
  98184. */
  98185. HighlightLayer.prototype.removeMesh = function (mesh) {
  98186. if (!this._meshes) {
  98187. return;
  98188. }
  98189. var meshHighlight = this._meshes[mesh.uniqueId];
  98190. if (meshHighlight) {
  98191. if (meshHighlight.observerHighlight) {
  98192. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98193. }
  98194. if (meshHighlight.observerDefault) {
  98195. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98196. }
  98197. delete this._meshes[mesh.uniqueId];
  98198. }
  98199. this._shouldRender = false;
  98200. for (var meshHighlightToCheck in this._meshes) {
  98201. if (this._meshes[meshHighlightToCheck]) {
  98202. this._shouldRender = true;
  98203. break;
  98204. }
  98205. }
  98206. };
  98207. /**
  98208. * Force the stencil to the normal expected value for none glowing parts
  98209. */
  98210. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  98211. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  98212. };
  98213. /**
  98214. * Free any resources and references associated to a mesh.
  98215. * Internal use
  98216. * @param mesh The mesh to free.
  98217. */
  98218. HighlightLayer.prototype._disposeMesh = function (mesh) {
  98219. this.removeMesh(mesh);
  98220. this.removeExcludedMesh(mesh);
  98221. };
  98222. /**
  98223. * Dispose the highlight layer and free resources.
  98224. */
  98225. HighlightLayer.prototype.dispose = function () {
  98226. if (this._meshes) {
  98227. // Clean mesh references
  98228. for (var id in this._meshes) {
  98229. var meshHighlight = this._meshes[id];
  98230. if (meshHighlight && meshHighlight.mesh) {
  98231. if (meshHighlight.observerHighlight) {
  98232. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98233. }
  98234. if (meshHighlight.observerDefault) {
  98235. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98236. }
  98237. }
  98238. }
  98239. this._meshes = null;
  98240. }
  98241. if (this._excludedMeshes) {
  98242. for (var id in this._excludedMeshes) {
  98243. var meshHighlight = this._excludedMeshes[id];
  98244. if (meshHighlight) {
  98245. if (meshHighlight.beforeRender) {
  98246. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  98247. }
  98248. if (meshHighlight.afterRender) {
  98249. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  98250. }
  98251. }
  98252. }
  98253. this._excludedMeshes = null;
  98254. }
  98255. _super.prototype.dispose.call(this);
  98256. };
  98257. /**
  98258. * Gets the class name of the effect layer
  98259. * @returns the string with the class name of the effect layer
  98260. */
  98261. HighlightLayer.prototype.getClassName = function () {
  98262. return "HighlightLayer";
  98263. };
  98264. /**
  98265. * Serializes this Highlight layer
  98266. * @returns a serialized Highlight layer object
  98267. */
  98268. HighlightLayer.prototype.serialize = function () {
  98269. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98270. serializationObject.customType = "BABYLON.HighlightLayer";
  98271. // Highlighted meshes
  98272. serializationObject.meshes = [];
  98273. if (this._meshes) {
  98274. for (var m in this._meshes) {
  98275. var mesh = this._meshes[m];
  98276. if (mesh) {
  98277. serializationObject.meshes.push({
  98278. glowEmissiveOnly: mesh.glowEmissiveOnly,
  98279. color: mesh.color.asArray(),
  98280. meshId: mesh.mesh.id
  98281. });
  98282. }
  98283. }
  98284. }
  98285. // Excluded meshes
  98286. serializationObject.excludedMeshes = [];
  98287. if (this._excludedMeshes) {
  98288. for (var e in this._excludedMeshes) {
  98289. var excludedMesh = this._excludedMeshes[e];
  98290. if (excludedMesh) {
  98291. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  98292. }
  98293. }
  98294. }
  98295. return serializationObject;
  98296. };
  98297. /**
  98298. * Creates a Highlight layer from parsed Highlight layer data
  98299. * @param parsedHightlightLayer defines the Highlight layer data
  98300. * @param scene defines the current scene
  98301. * @param rootUrl defines the root URL containing the Highlight layer information
  98302. * @returns a parsed Highlight layer
  98303. */
  98304. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  98305. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  98306. var index;
  98307. // Excluded meshes
  98308. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  98309. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  98310. if (mesh) {
  98311. hl.addExcludedMesh(mesh);
  98312. }
  98313. }
  98314. // Included meshes
  98315. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  98316. var highlightedMesh = parsedHightlightLayer.meshes[index];
  98317. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  98318. if (mesh) {
  98319. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  98320. }
  98321. }
  98322. return hl;
  98323. };
  98324. /**
  98325. * Effect Name of the highlight layer.
  98326. */
  98327. HighlightLayer.EffectName = "HighlightLayer";
  98328. /**
  98329. * The neutral color used during the preparation of the glow effect.
  98330. * This is black by default as the blend operation is a blend operation.
  98331. */
  98332. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  98333. /**
  98334. * Stencil value used for glowing meshes.
  98335. */
  98336. HighlightLayer.GlowingMeshStencilReference = 0x02;
  98337. /**
  98338. * Stencil value used for the other meshes in the scene.
  98339. */
  98340. HighlightLayer.NormalMeshStencilReference = 0x01;
  98341. __decorate([
  98342. BABYLON.serialize()
  98343. ], HighlightLayer.prototype, "innerGlow", void 0);
  98344. __decorate([
  98345. BABYLON.serialize()
  98346. ], HighlightLayer.prototype, "outerGlow", void 0);
  98347. __decorate([
  98348. BABYLON.serialize()
  98349. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  98350. __decorate([
  98351. BABYLON.serialize()
  98352. ], HighlightLayer.prototype, "blurVerticalSize", null);
  98353. __decorate([
  98354. BABYLON.serialize("options")
  98355. ], HighlightLayer.prototype, "_options", void 0);
  98356. return HighlightLayer;
  98357. }(BABYLON.EffectLayer));
  98358. BABYLON.HighlightLayer = HighlightLayer;
  98359. })(BABYLON || (BABYLON = {}));
  98360. //# sourceMappingURL=babylon.highlightLayer.js.map
  98361. var BABYLON;
  98362. (function (BABYLON) {
  98363. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  98364. for (var index = 0; index < this.effectLayers.length; index++) {
  98365. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  98366. return this.effectLayers[index];
  98367. }
  98368. }
  98369. return null;
  98370. };
  98371. /**
  98372. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  98373. *
  98374. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98375. * glowy meshes to your scene.
  98376. *
  98377. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  98378. */
  98379. var GlowLayer = /** @class */ (function (_super) {
  98380. __extends(GlowLayer, _super);
  98381. /**
  98382. * Instantiates a new glow Layer and references it to the scene.
  98383. * @param name The name of the layer
  98384. * @param scene The scene to use the layer in
  98385. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  98386. */
  98387. function GlowLayer(name, scene, options) {
  98388. var _this = _super.call(this, name, scene) || this;
  98389. _this._intensity = 1.0;
  98390. _this._includedOnlyMeshes = [];
  98391. _this._excludedMeshes = [];
  98392. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  98393. // Adapt options
  98394. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  98395. // Initialize the layer
  98396. _this._init({
  98397. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  98398. camera: _this._options.camera,
  98399. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  98400. mainTextureRatio: _this._options.mainTextureRatio,
  98401. renderingGroupId: _this._options.renderingGroupId
  98402. });
  98403. return _this;
  98404. }
  98405. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  98406. /**
  98407. * Gets the kernel size of the blur.
  98408. */
  98409. get: function () {
  98410. return this._horizontalBlurPostprocess1.kernel;
  98411. },
  98412. /**
  98413. * Sets the kernel size of the blur.
  98414. */
  98415. set: function (value) {
  98416. this._horizontalBlurPostprocess1.kernel = value;
  98417. this._verticalBlurPostprocess1.kernel = value;
  98418. this._horizontalBlurPostprocess2.kernel = value;
  98419. this._verticalBlurPostprocess2.kernel = value;
  98420. },
  98421. enumerable: true,
  98422. configurable: true
  98423. });
  98424. Object.defineProperty(GlowLayer.prototype, "intensity", {
  98425. /**
  98426. * Gets the glow intensity.
  98427. */
  98428. get: function () {
  98429. return this._intensity;
  98430. },
  98431. /**
  98432. * Sets the glow intensity.
  98433. */
  98434. set: function (value) {
  98435. this._intensity = value;
  98436. },
  98437. enumerable: true,
  98438. configurable: true
  98439. });
  98440. /**
  98441. * Get the effect name of the layer.
  98442. * @return The effect name
  98443. */
  98444. GlowLayer.prototype.getEffectName = function () {
  98445. return GlowLayer.EffectName;
  98446. };
  98447. /**
  98448. * Create the merge effect. This is the shader use to blit the information back
  98449. * to the main canvas at the end of the scene rendering.
  98450. */
  98451. GlowLayer.prototype._createMergeEffect = function () {
  98452. // Effect
  98453. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  98454. };
  98455. /**
  98456. * Creates the render target textures and post processes used in the glow layer.
  98457. */
  98458. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  98459. var _this = this;
  98460. var blurTextureWidth = this._mainTextureDesiredSize.width;
  98461. var blurTextureHeight = this._mainTextureDesiredSize.height;
  98462. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98463. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98464. var textureType = 0;
  98465. if (this._engine.getCaps().textureHalfFloatRender) {
  98466. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98467. }
  98468. else {
  98469. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98470. }
  98471. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  98472. width: blurTextureWidth,
  98473. height: blurTextureHeight
  98474. }, this._scene, false, true, textureType);
  98475. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98476. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98477. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98478. this._blurTexture1.renderParticles = false;
  98479. this._blurTexture1.ignoreCameraViewport = true;
  98480. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  98481. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  98482. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  98483. width: blurTextureWidth2,
  98484. height: blurTextureHeight2
  98485. }, this._scene, false, true, textureType);
  98486. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98487. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98488. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98489. this._blurTexture2.renderParticles = false;
  98490. this._blurTexture2.ignoreCameraViewport = true;
  98491. this._textures = [this._blurTexture1, this._blurTexture2];
  98492. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98493. width: blurTextureWidth,
  98494. height: blurTextureHeight
  98495. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98496. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  98497. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  98498. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  98499. effect.setTexture("textureSampler", _this._mainTexture);
  98500. });
  98501. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98502. width: blurTextureWidth,
  98503. height: blurTextureHeight
  98504. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98505. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98506. width: blurTextureWidth2,
  98507. height: blurTextureHeight2
  98508. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98509. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  98510. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  98511. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  98512. effect.setTexture("textureSampler", _this._blurTexture1);
  98513. });
  98514. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98515. width: blurTextureWidth2,
  98516. height: blurTextureHeight2
  98517. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98518. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98519. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  98520. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98521. this._mainTexture.samples = this._options.mainTextureSamples;
  98522. this._mainTexture.onAfterUnbindObservable.add(function () {
  98523. var internalTexture = _this._blurTexture1.getInternalTexture();
  98524. if (internalTexture) {
  98525. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  98526. internalTexture = _this._blurTexture2.getInternalTexture();
  98527. if (internalTexture) {
  98528. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  98529. }
  98530. }
  98531. });
  98532. // Prevent autoClear.
  98533. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98534. };
  98535. /**
  98536. * Checks for the readiness of the element composing the layer.
  98537. * @param subMesh the mesh to check for
  98538. * @param useInstances specify wether or not to use instances to render the mesh
  98539. * @param emissiveTexture the associated emissive texture used to generate the glow
  98540. * @return true if ready otherwise, false
  98541. */
  98542. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  98543. var material = subMesh.getMaterial();
  98544. var mesh = subMesh.getRenderingMesh();
  98545. if (!material || !mesh) {
  98546. return false;
  98547. }
  98548. var emissiveTexture = material.emissiveTexture;
  98549. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98550. };
  98551. /**
  98552. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98553. */
  98554. GlowLayer.prototype.needStencil = function () {
  98555. return false;
  98556. };
  98557. /**
  98558. * Implementation specific of rendering the generating effect on the main canvas.
  98559. * @param effect The effect used to render through
  98560. */
  98561. GlowLayer.prototype._internalRender = function (effect) {
  98562. // Texture
  98563. effect.setTexture("textureSampler", this._blurTexture1);
  98564. effect.setTexture("textureSampler2", this._blurTexture2);
  98565. effect.setFloat("offset", this._intensity);
  98566. // Cache
  98567. var engine = this._engine;
  98568. var previousStencilBuffer = engine.getStencilBuffer();
  98569. // Draw order
  98570. engine.setStencilBuffer(false);
  98571. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98572. // Draw order
  98573. engine.setStencilBuffer(previousStencilBuffer);
  98574. };
  98575. /**
  98576. * Sets the required values for both the emissive texture and and the main color.
  98577. */
  98578. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98579. var textureLevel = 1.0;
  98580. if (this.customEmissiveTextureSelector) {
  98581. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  98582. }
  98583. else {
  98584. if (material) {
  98585. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98586. if (this._emissiveTextureAndColor.texture) {
  98587. textureLevel = this._emissiveTextureAndColor.texture.level;
  98588. }
  98589. }
  98590. else {
  98591. this._emissiveTextureAndColor.texture = null;
  98592. }
  98593. }
  98594. if (this.customEmissiveColorSelector) {
  98595. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  98596. }
  98597. else {
  98598. if (material.emissiveColor) {
  98599. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  98600. }
  98601. else {
  98602. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98603. }
  98604. }
  98605. };
  98606. /**
  98607. * Returns true if the mesh should render, otherwise false.
  98608. * @param mesh The mesh to render
  98609. * @returns true if it should render otherwise false
  98610. */
  98611. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  98612. return this.hasMesh(mesh);
  98613. };
  98614. /**
  98615. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  98616. * @param mesh The mesh to exclude from the glow layer
  98617. */
  98618. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  98619. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  98620. this._excludedMeshes.push(mesh.uniqueId);
  98621. }
  98622. };
  98623. /**
  98624. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  98625. * @param mesh The mesh to remove
  98626. */
  98627. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  98628. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  98629. if (index !== -1) {
  98630. this._excludedMeshes.splice(index, 1);
  98631. }
  98632. };
  98633. /**
  98634. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  98635. * @param mesh The mesh to include in the glow layer
  98636. */
  98637. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  98638. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  98639. this._includedOnlyMeshes.push(mesh.uniqueId);
  98640. }
  98641. };
  98642. /**
  98643. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  98644. * @param mesh The mesh to remove
  98645. */
  98646. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  98647. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  98648. if (index !== -1) {
  98649. this._includedOnlyMeshes.splice(index, 1);
  98650. }
  98651. };
  98652. /**
  98653. * Determine if a given mesh will be used in the glow layer
  98654. * @param mesh The mesh to test
  98655. * @returns true if the mesh will be highlighted by the current glow layer
  98656. */
  98657. GlowLayer.prototype.hasMesh = function (mesh) {
  98658. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98659. return false;
  98660. }
  98661. // Included Mesh
  98662. if (this._includedOnlyMeshes.length) {
  98663. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  98664. }
  98665. ;
  98666. // Excluded Mesh
  98667. if (this._excludedMeshes.length) {
  98668. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  98669. }
  98670. ;
  98671. return true;
  98672. };
  98673. /**
  98674. * Free any resources and references associated to a mesh.
  98675. * Internal use
  98676. * @param mesh The mesh to free.
  98677. */
  98678. GlowLayer.prototype._disposeMesh = function (mesh) {
  98679. this.removeIncludedOnlyMesh(mesh);
  98680. this.removeExcludedMesh(mesh);
  98681. };
  98682. /**
  98683. * Gets the class name of the effect layer
  98684. * @returns the string with the class name of the effect layer
  98685. */
  98686. GlowLayer.prototype.getClassName = function () {
  98687. return "GlowLayer";
  98688. };
  98689. /**
  98690. * Serializes this glow layer
  98691. * @returns a serialized glow layer object
  98692. */
  98693. GlowLayer.prototype.serialize = function () {
  98694. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98695. serializationObject.customType = "BABYLON.GlowLayer";
  98696. var index;
  98697. // Included meshes
  98698. serializationObject.includedMeshes = [];
  98699. if (this._includedOnlyMeshes.length) {
  98700. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  98701. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  98702. if (mesh) {
  98703. serializationObject.includedMeshes.push(mesh.id);
  98704. }
  98705. }
  98706. }
  98707. // Excluded meshes
  98708. serializationObject.excludedMeshes = [];
  98709. if (this._excludedMeshes.length) {
  98710. for (index = 0; index < this._excludedMeshes.length; index++) {
  98711. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  98712. if (mesh) {
  98713. serializationObject.excludedMeshes.push(mesh.id);
  98714. }
  98715. }
  98716. }
  98717. return serializationObject;
  98718. };
  98719. /**
  98720. * Creates a Glow Layer from parsed glow layer data
  98721. * @param parsedGlowLayer defines glow layer data
  98722. * @param scene defines the current scene
  98723. * @param rootUrl defines the root URL containing the glow layer information
  98724. * @returns a parsed Glow Layer
  98725. */
  98726. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  98727. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  98728. var index;
  98729. // Excluded meshes
  98730. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  98731. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  98732. if (mesh) {
  98733. gl.addExcludedMesh(mesh);
  98734. }
  98735. }
  98736. // Included meshes
  98737. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  98738. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  98739. if (mesh) {
  98740. gl.addIncludedOnlyMesh(mesh);
  98741. }
  98742. }
  98743. return gl;
  98744. };
  98745. /**
  98746. * Effect Name of the layer.
  98747. */
  98748. GlowLayer.EffectName = "GlowLayer";
  98749. /**
  98750. * The default blur kernel size used for the glow.
  98751. */
  98752. GlowLayer.DefaultBlurKernelSize = 32;
  98753. /**
  98754. * The default texture size ratio used for the glow.
  98755. */
  98756. GlowLayer.DefaultTextureRatio = 0.5;
  98757. __decorate([
  98758. BABYLON.serialize()
  98759. ], GlowLayer.prototype, "blurKernelSize", null);
  98760. __decorate([
  98761. BABYLON.serialize()
  98762. ], GlowLayer.prototype, "intensity", null);
  98763. __decorate([
  98764. BABYLON.serialize("options")
  98765. ], GlowLayer.prototype, "_options", void 0);
  98766. return GlowLayer;
  98767. }(BABYLON.EffectLayer));
  98768. BABYLON.GlowLayer = GlowLayer;
  98769. })(BABYLON || (BABYLON = {}));
  98770. //# sourceMappingURL=babylon.glowLayer.js.map
  98771. var BABYLON;
  98772. (function (BABYLON) {
  98773. /**
  98774. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  98775. */
  98776. var AssetTaskState;
  98777. (function (AssetTaskState) {
  98778. /**
  98779. * Initialization
  98780. */
  98781. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  98782. /**
  98783. * Running
  98784. */
  98785. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  98786. /**
  98787. * Done
  98788. */
  98789. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  98790. /**
  98791. * Error
  98792. */
  98793. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  98794. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  98795. /**
  98796. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  98797. */
  98798. var AbstractAssetTask = /** @class */ (function () {
  98799. /**
  98800. * Creates a new {BABYLON.AssetsManager}
  98801. * @param name defines the name of the task
  98802. */
  98803. function AbstractAssetTask(
  98804. /**
  98805. * Task name
  98806. */ name) {
  98807. this.name = name;
  98808. this._isCompleted = false;
  98809. this._taskState = AssetTaskState.INIT;
  98810. }
  98811. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98812. /**
  98813. * Get if the task is completed
  98814. */
  98815. get: function () {
  98816. return this._isCompleted;
  98817. },
  98818. enumerable: true,
  98819. configurable: true
  98820. });
  98821. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98822. /**
  98823. * Gets the current state of the task
  98824. */
  98825. get: function () {
  98826. return this._taskState;
  98827. },
  98828. enumerable: true,
  98829. configurable: true
  98830. });
  98831. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98832. /**
  98833. * Gets the current error object (if task is in error)
  98834. */
  98835. get: function () {
  98836. return this._errorObject;
  98837. },
  98838. enumerable: true,
  98839. configurable: true
  98840. });
  98841. /**
  98842. * Internal only
  98843. * @hidden
  98844. */
  98845. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98846. if (this._errorObject) {
  98847. return;
  98848. }
  98849. this._errorObject = {
  98850. message: message,
  98851. exception: exception
  98852. };
  98853. };
  98854. /**
  98855. * Execute the current task
  98856. * @param scene defines the scene where you want your assets to be loaded
  98857. * @param onSuccess is a callback called when the task is successfully executed
  98858. * @param onError is a callback called if an error occurs
  98859. */
  98860. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98861. var _this = this;
  98862. this._taskState = AssetTaskState.RUNNING;
  98863. this.runTask(scene, function () {
  98864. _this.onDoneCallback(onSuccess, onError);
  98865. }, function (msg, exception) {
  98866. _this.onErrorCallback(onError, msg, exception);
  98867. });
  98868. };
  98869. /**
  98870. * Execute the current task
  98871. * @param scene defines the scene where you want your assets to be loaded
  98872. * @param onSuccess is a callback called when the task is successfully executed
  98873. * @param onError is a callback called if an error occurs
  98874. */
  98875. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98876. throw new Error("runTask is not implemented");
  98877. };
  98878. /**
  98879. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98880. * This can be used with failed tasks that have the reason for failure fixed.
  98881. */
  98882. AbstractAssetTask.prototype.reset = function () {
  98883. this._taskState = AssetTaskState.INIT;
  98884. };
  98885. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98886. this._taskState = AssetTaskState.ERROR;
  98887. this._errorObject = {
  98888. message: message,
  98889. exception: exception
  98890. };
  98891. if (this.onError) {
  98892. this.onError(this, message, exception);
  98893. }
  98894. onError();
  98895. };
  98896. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98897. try {
  98898. this._taskState = AssetTaskState.DONE;
  98899. this._isCompleted = true;
  98900. if (this.onSuccess) {
  98901. this.onSuccess(this);
  98902. }
  98903. onSuccess();
  98904. }
  98905. catch (e) {
  98906. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98907. }
  98908. };
  98909. return AbstractAssetTask;
  98910. }());
  98911. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98912. /**
  98913. * Class used to share progress information about assets loading
  98914. */
  98915. var AssetsProgressEvent = /** @class */ (function () {
  98916. /**
  98917. * Creates a {BABYLON.AssetsProgressEvent}
  98918. * @param remainingCount defines the number of remaining tasks to process
  98919. * @param totalCount defines the total number of tasks
  98920. * @param task defines the task that was just processed
  98921. */
  98922. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98923. this.remainingCount = remainingCount;
  98924. this.totalCount = totalCount;
  98925. this.task = task;
  98926. }
  98927. return AssetsProgressEvent;
  98928. }());
  98929. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98930. /**
  98931. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98932. */
  98933. var MeshAssetTask = /** @class */ (function (_super) {
  98934. __extends(MeshAssetTask, _super);
  98935. /**
  98936. * Creates a new {BABYLON.MeshAssetTask}
  98937. * @param name defines the name of the task
  98938. * @param meshesNames defines the list of mesh's names you want to load
  98939. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98940. * @param sceneFilename defines the filename of the scene to load from
  98941. */
  98942. function MeshAssetTask(
  98943. /**
  98944. * Defines the name of the task
  98945. */
  98946. name,
  98947. /**
  98948. * Defines the list of mesh's names you want to load
  98949. */
  98950. meshesNames,
  98951. /**
  98952. * Defines the root url to use as a base to load your meshes and associated resources
  98953. */
  98954. rootUrl,
  98955. /**
  98956. * Defines the filename of the scene to load from
  98957. */
  98958. sceneFilename) {
  98959. var _this = _super.call(this, name) || this;
  98960. _this.name = name;
  98961. _this.meshesNames = meshesNames;
  98962. _this.rootUrl = rootUrl;
  98963. _this.sceneFilename = sceneFilename;
  98964. return _this;
  98965. }
  98966. /**
  98967. * Execute the current task
  98968. * @param scene defines the scene where you want your assets to be loaded
  98969. * @param onSuccess is a callback called when the task is successfully executed
  98970. * @param onError is a callback called if an error occurs
  98971. */
  98972. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98973. var _this = this;
  98974. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98975. _this.loadedMeshes = meshes;
  98976. _this.loadedParticleSystems = particleSystems;
  98977. _this.loadedSkeletons = skeletons;
  98978. onSuccess();
  98979. }, null, function (scene, message, exception) {
  98980. onError(message, exception);
  98981. });
  98982. };
  98983. return MeshAssetTask;
  98984. }(AbstractAssetTask));
  98985. BABYLON.MeshAssetTask = MeshAssetTask;
  98986. /**
  98987. * Define a task used by {BABYLON.AssetsManager} to load text content
  98988. */
  98989. var TextFileAssetTask = /** @class */ (function (_super) {
  98990. __extends(TextFileAssetTask, _super);
  98991. /**
  98992. * Creates a new TextFileAssetTask object
  98993. * @param name defines the name of the task
  98994. * @param url defines the location of the file to load
  98995. */
  98996. function TextFileAssetTask(
  98997. /**
  98998. * Defines the name of the task
  98999. */
  99000. name,
  99001. /**
  99002. * Defines the location of the file to load
  99003. */
  99004. url) {
  99005. var _this = _super.call(this, name) || this;
  99006. _this.name = name;
  99007. _this.url = url;
  99008. return _this;
  99009. }
  99010. /**
  99011. * Execute the current task
  99012. * @param scene defines the scene where you want your assets to be loaded
  99013. * @param onSuccess is a callback called when the task is successfully executed
  99014. * @param onError is a callback called if an error occurs
  99015. */
  99016. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99017. var _this = this;
  99018. scene._loadFile(this.url, function (data) {
  99019. _this.text = data;
  99020. onSuccess();
  99021. }, undefined, false, false, function (request, exception) {
  99022. if (request) {
  99023. onError(request.status + " " + request.statusText, exception);
  99024. }
  99025. });
  99026. };
  99027. return TextFileAssetTask;
  99028. }(AbstractAssetTask));
  99029. BABYLON.TextFileAssetTask = TextFileAssetTask;
  99030. /**
  99031. * Define a task used by {BABYLON.AssetsManager} to load binary data
  99032. */
  99033. var BinaryFileAssetTask = /** @class */ (function (_super) {
  99034. __extends(BinaryFileAssetTask, _super);
  99035. /**
  99036. * Creates a new BinaryFileAssetTask object
  99037. * @param name defines the name of the new task
  99038. * @param url defines the location of the file to load
  99039. */
  99040. function BinaryFileAssetTask(
  99041. /**
  99042. * Defines the name of the task
  99043. */
  99044. name,
  99045. /**
  99046. * Defines the location of the file to load
  99047. */
  99048. url) {
  99049. var _this = _super.call(this, name) || this;
  99050. _this.name = name;
  99051. _this.url = url;
  99052. return _this;
  99053. }
  99054. /**
  99055. * Execute the current task
  99056. * @param scene defines the scene where you want your assets to be loaded
  99057. * @param onSuccess is a callback called when the task is successfully executed
  99058. * @param onError is a callback called if an error occurs
  99059. */
  99060. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99061. var _this = this;
  99062. scene._loadFile(this.url, function (data) {
  99063. _this.data = data;
  99064. onSuccess();
  99065. }, undefined, true, true, function (request, exception) {
  99066. if (request) {
  99067. onError(request.status + " " + request.statusText, exception);
  99068. }
  99069. });
  99070. };
  99071. return BinaryFileAssetTask;
  99072. }(AbstractAssetTask));
  99073. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  99074. /**
  99075. * Define a task used by {BABYLON.AssetsManager} to load images
  99076. */
  99077. var ImageAssetTask = /** @class */ (function (_super) {
  99078. __extends(ImageAssetTask, _super);
  99079. /**
  99080. * Creates a new ImageAssetTask
  99081. * @param name defines the name of the task
  99082. * @param url defines the location of the image to load
  99083. */
  99084. function ImageAssetTask(
  99085. /**
  99086. * Defines the name of the task
  99087. */
  99088. name,
  99089. /**
  99090. * Defines the location of the image to load
  99091. */
  99092. url) {
  99093. var _this = _super.call(this, name) || this;
  99094. _this.name = name;
  99095. _this.url = url;
  99096. return _this;
  99097. }
  99098. /**
  99099. * Execute the current task
  99100. * @param scene defines the scene where you want your assets to be loaded
  99101. * @param onSuccess is a callback called when the task is successfully executed
  99102. * @param onError is a callback called if an error occurs
  99103. */
  99104. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99105. var _this = this;
  99106. var img = new Image();
  99107. BABYLON.Tools.SetCorsBehavior(this.url, img);
  99108. img.onload = function () {
  99109. _this.image = img;
  99110. onSuccess();
  99111. };
  99112. img.onerror = function (err) {
  99113. onError("Error loading image", err);
  99114. };
  99115. img.src = this.url;
  99116. };
  99117. return ImageAssetTask;
  99118. }(AbstractAssetTask));
  99119. BABYLON.ImageAssetTask = ImageAssetTask;
  99120. /**
  99121. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  99122. */
  99123. var TextureAssetTask = /** @class */ (function (_super) {
  99124. __extends(TextureAssetTask, _super);
  99125. /**
  99126. * Creates a new TextureAssetTask object
  99127. * @param name defines the name of the task
  99128. * @param url defines the location of the file to load
  99129. * @param noMipmap defines if mipmap should not be generated (default is false)
  99130. * @param invertY defines if texture must be inverted on Y axis (default is false)
  99131. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99132. */
  99133. function TextureAssetTask(
  99134. /**
  99135. * Defines the name of the task
  99136. */
  99137. name,
  99138. /**
  99139. * Defines the location of the file to load
  99140. */
  99141. url,
  99142. /**
  99143. * Defines if mipmap should not be generated (default is false)
  99144. */
  99145. noMipmap,
  99146. /**
  99147. * Defines if texture must be inverted on Y axis (default is false)
  99148. */
  99149. invertY,
  99150. /**
  99151. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99152. */
  99153. samplingMode) {
  99154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99155. var _this = _super.call(this, name) || this;
  99156. _this.name = name;
  99157. _this.url = url;
  99158. _this.noMipmap = noMipmap;
  99159. _this.invertY = invertY;
  99160. _this.samplingMode = samplingMode;
  99161. return _this;
  99162. }
  99163. /**
  99164. * Execute the current task
  99165. * @param scene defines the scene where you want your assets to be loaded
  99166. * @param onSuccess is a callback called when the task is successfully executed
  99167. * @param onError is a callback called if an error occurs
  99168. */
  99169. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99170. var onload = function () {
  99171. onSuccess();
  99172. };
  99173. var onerror = function (message, exception) {
  99174. onError(message, exception);
  99175. };
  99176. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  99177. };
  99178. return TextureAssetTask;
  99179. }(AbstractAssetTask));
  99180. BABYLON.TextureAssetTask = TextureAssetTask;
  99181. /**
  99182. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  99183. */
  99184. var CubeTextureAssetTask = /** @class */ (function (_super) {
  99185. __extends(CubeTextureAssetTask, _super);
  99186. /**
  99187. * Creates a new CubeTextureAssetTask
  99188. * @param name defines the name of the task
  99189. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99190. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99191. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99192. * @param files defines the explicit list of files (undefined by default)
  99193. */
  99194. function CubeTextureAssetTask(
  99195. /**
  99196. * Defines the name of the task
  99197. */
  99198. name,
  99199. /**
  99200. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99201. */
  99202. url,
  99203. /**
  99204. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99205. */
  99206. extensions,
  99207. /**
  99208. * Defines if mipmaps should not be generated (default is false)
  99209. */
  99210. noMipmap,
  99211. /**
  99212. * Defines the explicit list of files (undefined by default)
  99213. */
  99214. files) {
  99215. var _this = _super.call(this, name) || this;
  99216. _this.name = name;
  99217. _this.url = url;
  99218. _this.extensions = extensions;
  99219. _this.noMipmap = noMipmap;
  99220. _this.files = files;
  99221. return _this;
  99222. }
  99223. /**
  99224. * Execute the current task
  99225. * @param scene defines the scene where you want your assets to be loaded
  99226. * @param onSuccess is a callback called when the task is successfully executed
  99227. * @param onError is a callback called if an error occurs
  99228. */
  99229. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99230. var onload = function () {
  99231. onSuccess();
  99232. };
  99233. var onerror = function (message, exception) {
  99234. onError(message, exception);
  99235. };
  99236. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  99237. };
  99238. return CubeTextureAssetTask;
  99239. }(AbstractAssetTask));
  99240. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  99241. /**
  99242. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  99243. */
  99244. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  99245. __extends(HDRCubeTextureAssetTask, _super);
  99246. /**
  99247. * Creates a new HDRCubeTextureAssetTask object
  99248. * @param name defines the name of the task
  99249. * @param url defines the location of the file to load
  99250. * @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.
  99251. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99252. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99253. * @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)
  99254. * @param reserved Internal use only
  99255. */
  99256. function HDRCubeTextureAssetTask(
  99257. /**
  99258. * Defines the name of the task
  99259. */
  99260. name,
  99261. /**
  99262. * Defines the location of the file to load
  99263. */
  99264. url,
  99265. /**
  99266. * Defines the desired size (the more it increases the longer the generation will be)
  99267. */
  99268. size,
  99269. /**
  99270. * Defines if mipmaps should not be generated (default is false)
  99271. */
  99272. noMipmap,
  99273. /**
  99274. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99275. */
  99276. generateHarmonics,
  99277. /**
  99278. * 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)
  99279. */
  99280. gammaSpace,
  99281. /**
  99282. * Internal Use Only
  99283. */
  99284. reserved) {
  99285. if (noMipmap === void 0) { noMipmap = false; }
  99286. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99287. if (gammaSpace === void 0) { gammaSpace = false; }
  99288. if (reserved === void 0) { reserved = false; }
  99289. var _this = _super.call(this, name) || this;
  99290. _this.name = name;
  99291. _this.url = url;
  99292. _this.size = size;
  99293. _this.noMipmap = noMipmap;
  99294. _this.generateHarmonics = generateHarmonics;
  99295. _this.gammaSpace = gammaSpace;
  99296. _this.reserved = reserved;
  99297. return _this;
  99298. }
  99299. /**
  99300. * Execute the current task
  99301. * @param scene defines the scene where you want your assets to be loaded
  99302. * @param onSuccess is a callback called when the task is successfully executed
  99303. * @param onError is a callback called if an error occurs
  99304. */
  99305. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99306. var onload = function () {
  99307. onSuccess();
  99308. };
  99309. var onerror = function (message, exception) {
  99310. onError(message, exception);
  99311. };
  99312. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  99313. };
  99314. return HDRCubeTextureAssetTask;
  99315. }(AbstractAssetTask));
  99316. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  99317. /**
  99318. * This class can be used to easily import assets into a scene
  99319. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  99320. */
  99321. var AssetsManager = /** @class */ (function () {
  99322. /**
  99323. * Creates a new AssetsManager
  99324. * @param scene defines the scene to work on
  99325. */
  99326. function AssetsManager(scene) {
  99327. this._isLoading = false;
  99328. this._tasks = new Array();
  99329. this._waitingTasksCount = 0;
  99330. this._totalTasksCount = 0;
  99331. /**
  99332. * Observable called when all tasks are processed
  99333. */
  99334. this.onTaskSuccessObservable = new BABYLON.Observable();
  99335. /**
  99336. * Observable called when a task had an error
  99337. */
  99338. this.onTaskErrorObservable = new BABYLON.Observable();
  99339. /**
  99340. * Observable called when a task is successful
  99341. */
  99342. this.onTasksDoneObservable = new BABYLON.Observable();
  99343. /**
  99344. * Observable called when a task is done (whatever the result is)
  99345. */
  99346. this.onProgressObservable = new BABYLON.Observable();
  99347. /**
  99348. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  99349. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  99350. */
  99351. this.useDefaultLoadingScreen = true;
  99352. this._scene = scene;
  99353. }
  99354. /**
  99355. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  99356. * @param taskName defines the name of the new task
  99357. * @param meshesNames defines the name of meshes to load
  99358. * @param rootUrl defines the root url to use to locate files
  99359. * @param sceneFilename defines the filename of the scene file
  99360. * @returns a new {BABYLON.MeshAssetTask} object
  99361. */
  99362. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  99363. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  99364. this._tasks.push(task);
  99365. return task;
  99366. };
  99367. /**
  99368. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  99369. * @param taskName defines the name of the new task
  99370. * @param url defines the url of the file to load
  99371. * @returns a new {BABYLON.TextFileAssetTask} object
  99372. */
  99373. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  99374. var task = new TextFileAssetTask(taskName, url);
  99375. this._tasks.push(task);
  99376. return task;
  99377. };
  99378. /**
  99379. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  99380. * @param taskName defines the name of the new task
  99381. * @param url defines the url of the file to load
  99382. * @returns a new {BABYLON.BinaryFileAssetTask} object
  99383. */
  99384. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  99385. var task = new BinaryFileAssetTask(taskName, url);
  99386. this._tasks.push(task);
  99387. return task;
  99388. };
  99389. /**
  99390. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  99391. * @param taskName defines the name of the new task
  99392. * @param url defines the url of the file to load
  99393. * @returns a new {BABYLON.ImageAssetTask} object
  99394. */
  99395. AssetsManager.prototype.addImageTask = function (taskName, url) {
  99396. var task = new ImageAssetTask(taskName, url);
  99397. this._tasks.push(task);
  99398. return task;
  99399. };
  99400. /**
  99401. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  99402. * @param taskName defines the name of the new task
  99403. * @param url defines the url of the file to load
  99404. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99405. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  99406. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  99407. * @returns a new {BABYLON.TextureAssetTask} object
  99408. */
  99409. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  99410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99411. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  99412. this._tasks.push(task);
  99413. return task;
  99414. };
  99415. /**
  99416. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  99417. * @param taskName defines the name of the new task
  99418. * @param url defines the url of the file to load
  99419. * @param extensions defines the extension to use to load the cube map (can be null)
  99420. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99421. * @param files defines the list of files to load (can be null)
  99422. * @returns a new {BABYLON.CubeTextureAssetTask} object
  99423. */
  99424. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  99425. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  99426. this._tasks.push(task);
  99427. return task;
  99428. };
  99429. /**
  99430. *
  99431. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  99432. * @param taskName defines the name of the new task
  99433. * @param url defines the url of the file to load
  99434. * @param size defines the size you want for the cubemap (can be null)
  99435. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99436. * @param generateHarmonics defines if you want to automatically generate (true by default)
  99437. * @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)
  99438. * @param reserved Internal use only
  99439. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  99440. */
  99441. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  99442. if (noMipmap === void 0) { noMipmap = false; }
  99443. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99444. if (gammaSpace === void 0) { gammaSpace = false; }
  99445. if (reserved === void 0) { reserved = false; }
  99446. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  99447. this._tasks.push(task);
  99448. return task;
  99449. };
  99450. /**
  99451. * Remove a task from the assets manager.
  99452. * @param task the task to remove
  99453. */
  99454. AssetsManager.prototype.removeTask = function (task) {
  99455. var index = this._tasks.indexOf(task);
  99456. if (index > -1) {
  99457. this._tasks.splice(index, 1);
  99458. }
  99459. };
  99460. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  99461. this._waitingTasksCount--;
  99462. try {
  99463. if (this.onProgress) {
  99464. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  99465. }
  99466. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  99467. }
  99468. catch (e) {
  99469. BABYLON.Tools.Error("Error running progress callbacks.");
  99470. console.log(e);
  99471. }
  99472. if (this._waitingTasksCount === 0) {
  99473. try {
  99474. if (this.onFinish) {
  99475. this.onFinish(this._tasks);
  99476. }
  99477. // Let's remove successfull tasks
  99478. var currentTasks = this._tasks.slice();
  99479. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  99480. var task = currentTasks_1[_i];
  99481. if (task.taskState === AssetTaskState.DONE) {
  99482. var index = this._tasks.indexOf(task);
  99483. if (index > -1) {
  99484. this._tasks.splice(index, 1);
  99485. }
  99486. }
  99487. }
  99488. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99489. }
  99490. catch (e) {
  99491. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  99492. console.log(e);
  99493. }
  99494. this._isLoading = false;
  99495. this._scene.getEngine().hideLoadingUI();
  99496. }
  99497. };
  99498. AssetsManager.prototype._runTask = function (task) {
  99499. var _this = this;
  99500. var done = function () {
  99501. try {
  99502. if (_this.onTaskSuccess) {
  99503. _this.onTaskSuccess(task);
  99504. }
  99505. _this.onTaskSuccessObservable.notifyObservers(task);
  99506. _this._decreaseWaitingTasksCount(task);
  99507. }
  99508. catch (e) {
  99509. error("Error executing task success callbacks", e);
  99510. }
  99511. };
  99512. var error = function (message, exception) {
  99513. task._setErrorObject(message, exception);
  99514. if (_this.onTaskError) {
  99515. _this.onTaskError(task);
  99516. }
  99517. _this.onTaskErrorObservable.notifyObservers(task);
  99518. _this._decreaseWaitingTasksCount(task);
  99519. };
  99520. task.run(this._scene, done, error);
  99521. };
  99522. /**
  99523. * Reset the {BABYLON.AssetsManager} and remove all tasks
  99524. * @return the current instance of the {BABYLON.AssetsManager}
  99525. */
  99526. AssetsManager.prototype.reset = function () {
  99527. this._isLoading = false;
  99528. this._tasks = new Array();
  99529. return this;
  99530. };
  99531. /**
  99532. * Start the loading process
  99533. * @return the current instance of the {BABYLON.AssetsManager}
  99534. */
  99535. AssetsManager.prototype.load = function () {
  99536. if (this._isLoading) {
  99537. return this;
  99538. }
  99539. this._isLoading = true;
  99540. this._waitingTasksCount = this._tasks.length;
  99541. this._totalTasksCount = this._tasks.length;
  99542. if (this._waitingTasksCount === 0) {
  99543. this._isLoading = false;
  99544. if (this.onFinish) {
  99545. this.onFinish(this._tasks);
  99546. }
  99547. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99548. return this;
  99549. }
  99550. if (this.useDefaultLoadingScreen) {
  99551. this._scene.getEngine().displayLoadingUI();
  99552. }
  99553. for (var index = 0; index < this._tasks.length; index++) {
  99554. var task = this._tasks[index];
  99555. if (task.taskState === AssetTaskState.INIT) {
  99556. this._runTask(task);
  99557. }
  99558. }
  99559. return this;
  99560. };
  99561. return AssetsManager;
  99562. }());
  99563. BABYLON.AssetsManager = AssetsManager;
  99564. })(BABYLON || (BABYLON = {}));
  99565. //# sourceMappingURL=babylon.assetsManager.js.map
  99566. var BABYLON;
  99567. (function (BABYLON) {
  99568. var serializedGeometries = [];
  99569. var serializeGeometry = function (geometry, serializationGeometries) {
  99570. if (serializedGeometries[geometry.id]) {
  99571. return;
  99572. }
  99573. if (geometry.doNotSerialize) {
  99574. return;
  99575. }
  99576. if (geometry instanceof BABYLON.BoxGeometry) {
  99577. serializationGeometries.boxes.push(geometry.serialize());
  99578. }
  99579. else if (geometry instanceof BABYLON.SphereGeometry) {
  99580. serializationGeometries.spheres.push(geometry.serialize());
  99581. }
  99582. else if (geometry instanceof BABYLON.CylinderGeometry) {
  99583. serializationGeometries.cylinders.push(geometry.serialize());
  99584. }
  99585. else if (geometry instanceof BABYLON.TorusGeometry) {
  99586. serializationGeometries.toruses.push(geometry.serialize());
  99587. }
  99588. else if (geometry instanceof BABYLON.GroundGeometry) {
  99589. serializationGeometries.grounds.push(geometry.serialize());
  99590. }
  99591. else if (geometry instanceof BABYLON.Plane) {
  99592. serializationGeometries.planes.push(geometry.serialize());
  99593. }
  99594. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  99595. serializationGeometries.torusKnots.push(geometry.serialize());
  99596. }
  99597. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  99598. throw new Error("Unknown primitive type");
  99599. }
  99600. else {
  99601. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  99602. }
  99603. serializedGeometries[geometry.id] = true;
  99604. };
  99605. var serializeMesh = function (mesh, serializationScene) {
  99606. var serializationObject = {};
  99607. // Geometry
  99608. var geometry = mesh._geometry;
  99609. if (geometry) {
  99610. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  99611. // 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
  99612. serializeGeometry(geometry, serializationScene.geometries);
  99613. }
  99614. }
  99615. // Custom
  99616. if (mesh.serialize) {
  99617. mesh.serialize(serializationObject);
  99618. }
  99619. return serializationObject;
  99620. };
  99621. var finalizeSingleMesh = function (mesh, serializationObject) {
  99622. //only works if the mesh is already loaded
  99623. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99624. //serialize material
  99625. if (mesh.material) {
  99626. if (mesh.material instanceof BABYLON.MultiMaterial) {
  99627. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  99628. serializationObject.materials = serializationObject.materials || [];
  99629. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99630. serializationObject.multiMaterials.push(mesh.material.serialize());
  99631. var _loop_1 = function (submaterial) {
  99632. if (submaterial) {
  99633. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  99634. serializationObject.materials.push(submaterial.serialize());
  99635. }
  99636. }
  99637. };
  99638. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  99639. var submaterial = _a[_i];
  99640. _loop_1(submaterial);
  99641. }
  99642. }
  99643. }
  99644. else {
  99645. serializationObject.materials = serializationObject.materials || [];
  99646. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99647. serializationObject.materials.push(mesh.material.serialize());
  99648. }
  99649. }
  99650. }
  99651. //serialize geometry
  99652. var geometry = mesh._geometry;
  99653. if (geometry) {
  99654. if (!serializationObject.geometries) {
  99655. serializationObject.geometries = {};
  99656. serializationObject.geometries.boxes = [];
  99657. serializationObject.geometries.spheres = [];
  99658. serializationObject.geometries.cylinders = [];
  99659. serializationObject.geometries.toruses = [];
  99660. serializationObject.geometries.grounds = [];
  99661. serializationObject.geometries.planes = [];
  99662. serializationObject.geometries.torusKnots = [];
  99663. serializationObject.geometries.vertexData = [];
  99664. }
  99665. serializeGeometry(geometry, serializationObject.geometries);
  99666. }
  99667. // Skeletons
  99668. if (mesh.skeleton) {
  99669. serializationObject.skeletons = serializationObject.skeletons || [];
  99670. serializationObject.skeletons.push(mesh.skeleton.serialize());
  99671. }
  99672. //serialize the actual mesh
  99673. serializationObject.meshes = serializationObject.meshes || [];
  99674. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99675. }
  99676. };
  99677. var SceneSerializer = /** @class */ (function () {
  99678. function SceneSerializer() {
  99679. }
  99680. SceneSerializer.ClearCache = function () {
  99681. serializedGeometries = [];
  99682. };
  99683. SceneSerializer.Serialize = function (scene) {
  99684. var serializationObject = {};
  99685. SceneSerializer.ClearCache();
  99686. // Scene
  99687. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  99688. serializationObject.autoClear = scene.autoClear;
  99689. serializationObject.clearColor = scene.clearColor.asArray();
  99690. serializationObject.ambientColor = scene.ambientColor.asArray();
  99691. serializationObject.gravity = scene.gravity.asArray();
  99692. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  99693. serializationObject.workerCollisions = scene.workerCollisions;
  99694. // Fog
  99695. if (scene.fogMode && scene.fogMode !== 0) {
  99696. serializationObject.fogMode = scene.fogMode;
  99697. serializationObject.fogColor = scene.fogColor.asArray();
  99698. serializationObject.fogStart = scene.fogStart;
  99699. serializationObject.fogEnd = scene.fogEnd;
  99700. serializationObject.fogDensity = scene.fogDensity;
  99701. }
  99702. //Physics
  99703. if (scene.isPhysicsEnabled()) {
  99704. var physicEngine = scene.getPhysicsEngine();
  99705. if (physicEngine) {
  99706. serializationObject.physicsEnabled = true;
  99707. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  99708. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  99709. }
  99710. }
  99711. // Metadata
  99712. if (scene.metadata) {
  99713. serializationObject.metadata = scene.metadata;
  99714. }
  99715. // Morph targets
  99716. serializationObject.morphTargetManagers = [];
  99717. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  99718. var abstractMesh = _a[_i];
  99719. var manager = abstractMesh.morphTargetManager;
  99720. if (manager) {
  99721. serializationObject.morphTargetManagers.push(manager.serialize());
  99722. }
  99723. }
  99724. // Lights
  99725. serializationObject.lights = [];
  99726. var index;
  99727. var light;
  99728. for (index = 0; index < scene.lights.length; index++) {
  99729. light = scene.lights[index];
  99730. if (!light.doNotSerialize) {
  99731. serializationObject.lights.push(light.serialize());
  99732. }
  99733. }
  99734. // Cameras
  99735. serializationObject.cameras = [];
  99736. for (index = 0; index < scene.cameras.length; index++) {
  99737. var camera = scene.cameras[index];
  99738. if (!camera.doNotSerialize) {
  99739. serializationObject.cameras.push(camera.serialize());
  99740. }
  99741. }
  99742. if (scene.activeCamera) {
  99743. serializationObject.activeCameraID = scene.activeCamera.id;
  99744. }
  99745. // Animations
  99746. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  99747. // Materials
  99748. serializationObject.materials = [];
  99749. serializationObject.multiMaterials = [];
  99750. var material;
  99751. for (index = 0; index < scene.materials.length; index++) {
  99752. material = scene.materials[index];
  99753. if (!material.doNotSerialize) {
  99754. serializationObject.materials.push(material.serialize());
  99755. }
  99756. }
  99757. // MultiMaterials
  99758. serializationObject.multiMaterials = [];
  99759. for (index = 0; index < scene.multiMaterials.length; index++) {
  99760. var multiMaterial = scene.multiMaterials[index];
  99761. serializationObject.multiMaterials.push(multiMaterial.serialize());
  99762. }
  99763. // Environment texture
  99764. if (scene.environmentTexture) {
  99765. serializationObject.environmentTexture = scene.environmentTexture.name;
  99766. }
  99767. // Skeletons
  99768. serializationObject.skeletons = [];
  99769. for (index = 0; index < scene.skeletons.length; index++) {
  99770. var skeleton = scene.skeletons[index];
  99771. if (!skeleton.doNotSerialize) {
  99772. serializationObject.skeletons.push(skeleton.serialize());
  99773. }
  99774. }
  99775. // Transform nodes
  99776. serializationObject.transformNodes = [];
  99777. for (index = 0; index < scene.transformNodes.length; index++) {
  99778. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  99779. }
  99780. // Geometries
  99781. serializationObject.geometries = {};
  99782. serializationObject.geometries.boxes = [];
  99783. serializationObject.geometries.spheres = [];
  99784. serializationObject.geometries.cylinders = [];
  99785. serializationObject.geometries.toruses = [];
  99786. serializationObject.geometries.grounds = [];
  99787. serializationObject.geometries.planes = [];
  99788. serializationObject.geometries.torusKnots = [];
  99789. serializationObject.geometries.vertexData = [];
  99790. serializedGeometries = [];
  99791. var geometries = scene.getGeometries();
  99792. for (index = 0; index < geometries.length; index++) {
  99793. var geometry = geometries[index];
  99794. if (geometry.isReady()) {
  99795. serializeGeometry(geometry, serializationObject.geometries);
  99796. }
  99797. }
  99798. // Meshes
  99799. serializationObject.meshes = [];
  99800. for (index = 0; index < scene.meshes.length; index++) {
  99801. var abstractMesh = scene.meshes[index];
  99802. if (abstractMesh instanceof BABYLON.Mesh) {
  99803. var mesh = abstractMesh;
  99804. if (!mesh.doNotSerialize) {
  99805. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99806. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99807. }
  99808. }
  99809. }
  99810. }
  99811. // Particles Systems
  99812. serializationObject.particleSystems = [];
  99813. for (index = 0; index < scene.particleSystems.length; index++) {
  99814. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  99815. }
  99816. // Shadows
  99817. serializationObject.shadowGenerators = [];
  99818. for (index = 0; index < scene.lights.length; index++) {
  99819. light = scene.lights[index];
  99820. var shadowGenerator = light.getShadowGenerator();
  99821. if (shadowGenerator) {
  99822. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  99823. }
  99824. }
  99825. // Action Manager
  99826. if (scene.actionManager) {
  99827. serializationObject.actions = scene.actionManager.serialize("scene");
  99828. }
  99829. // Audio
  99830. serializationObject.sounds = [];
  99831. for (index = 0; index < scene.soundTracks.length; index++) {
  99832. var soundtrack = scene.soundTracks[index];
  99833. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99834. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99835. }
  99836. }
  99837. // Components
  99838. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99839. var component = _c[_b];
  99840. component.serialize(serializationObject);
  99841. }
  99842. return serializationObject;
  99843. };
  99844. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99845. if (withParents === void 0) { withParents = false; }
  99846. if (withChildren === void 0) { withChildren = false; }
  99847. var serializationObject = {};
  99848. SceneSerializer.ClearCache();
  99849. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99850. if (withParents || withChildren) {
  99851. //deliberate for loop! not for each, appended should be processed as well.
  99852. for (var i = 0; i < toSerialize.length; ++i) {
  99853. if (withChildren) {
  99854. toSerialize[i].getDescendants().forEach(function (node) {
  99855. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99856. toSerialize.push(node);
  99857. }
  99858. });
  99859. }
  99860. //make sure the array doesn't contain the object already
  99861. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99862. toSerialize.push(toSerialize[i].parent);
  99863. }
  99864. }
  99865. }
  99866. toSerialize.forEach(function (mesh) {
  99867. finalizeSingleMesh(mesh, serializationObject);
  99868. });
  99869. return serializationObject;
  99870. };
  99871. return SceneSerializer;
  99872. }());
  99873. BABYLON.SceneSerializer = SceneSerializer;
  99874. })(BABYLON || (BABYLON = {}));
  99875. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99876. var BABYLON;
  99877. (function (BABYLON) {
  99878. var ReflectionProbe = /** @class */ (function () {
  99879. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99880. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99881. var _this = this;
  99882. this.name = name;
  99883. this._viewMatrix = BABYLON.Matrix.Identity();
  99884. this._target = BABYLON.Vector3.Zero();
  99885. this._add = BABYLON.Vector3.Zero();
  99886. this._invertYAxis = false;
  99887. this.position = BABYLON.Vector3.Zero();
  99888. this._scene = scene;
  99889. this._scene.reflectionProbes.push(this);
  99890. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99891. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99892. switch (faceIndex) {
  99893. case 0:
  99894. _this._add.copyFromFloats(1, 0, 0);
  99895. break;
  99896. case 1:
  99897. _this._add.copyFromFloats(-1, 0, 0);
  99898. break;
  99899. case 2:
  99900. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99901. break;
  99902. case 3:
  99903. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99904. break;
  99905. case 4:
  99906. _this._add.copyFromFloats(0, 0, 1);
  99907. break;
  99908. case 5:
  99909. _this._add.copyFromFloats(0, 0, -1);
  99910. break;
  99911. }
  99912. if (_this._attachedMesh) {
  99913. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99914. }
  99915. _this.position.addToRef(_this._add, _this._target);
  99916. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99917. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99918. scene._forcedViewPosition = _this.position;
  99919. });
  99920. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99921. scene._forcedViewPosition = null;
  99922. scene.updateTransformMatrix(true);
  99923. });
  99924. if (scene.activeCamera) {
  99925. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99926. }
  99927. }
  99928. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99929. get: function () {
  99930. return this._renderTargetTexture.samples;
  99931. },
  99932. set: function (value) {
  99933. this._renderTargetTexture.samples = value;
  99934. },
  99935. enumerable: true,
  99936. configurable: true
  99937. });
  99938. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99939. get: function () {
  99940. return this._renderTargetTexture.refreshRate;
  99941. },
  99942. set: function (value) {
  99943. this._renderTargetTexture.refreshRate = value;
  99944. },
  99945. enumerable: true,
  99946. configurable: true
  99947. });
  99948. ReflectionProbe.prototype.getScene = function () {
  99949. return this._scene;
  99950. };
  99951. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99952. get: function () {
  99953. return this._renderTargetTexture;
  99954. },
  99955. enumerable: true,
  99956. configurable: true
  99957. });
  99958. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99959. get: function () {
  99960. return this._renderTargetTexture.renderList;
  99961. },
  99962. enumerable: true,
  99963. configurable: true
  99964. });
  99965. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99966. this._attachedMesh = mesh;
  99967. };
  99968. /**
  99969. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99970. *
  99971. * @param renderingGroupId The rendering group id corresponding to its index
  99972. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99973. */
  99974. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99975. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99976. };
  99977. ReflectionProbe.prototype.dispose = function () {
  99978. var index = this._scene.reflectionProbes.indexOf(this);
  99979. if (index !== -1) {
  99980. // Remove from the scene if found
  99981. this._scene.reflectionProbes.splice(index, 1);
  99982. }
  99983. if (this._renderTargetTexture) {
  99984. this._renderTargetTexture.dispose();
  99985. this._renderTargetTexture = null;
  99986. }
  99987. };
  99988. return ReflectionProbe;
  99989. }());
  99990. BABYLON.ReflectionProbe = ReflectionProbe;
  99991. })(BABYLON || (BABYLON = {}));
  99992. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99993. var BABYLON;
  99994. (function (BABYLON) {
  99995. /**
  99996. * Defines the layer scene component responsible to manage any layers
  99997. * in a given scene.
  99998. */
  99999. var LayerSceneComponent = /** @class */ (function () {
  100000. /**
  100001. * Creates a new instance of the component for the given scene
  100002. * @param scene Defines the scene to register the component in
  100003. */
  100004. function LayerSceneComponent(scene) {
  100005. /**
  100006. * The component name helpfull to identify the component in the list of scene components.
  100007. */
  100008. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  100009. this.scene = scene;
  100010. this._engine = scene.getEngine();
  100011. scene.layers = new Array();
  100012. }
  100013. /**
  100014. * Registers the component in a given scene
  100015. */
  100016. LayerSceneComponent.prototype.register = function () {
  100017. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  100018. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  100019. };
  100020. /**
  100021. * Rebuilds the elements related to this component in case of
  100022. * context lost for instance.
  100023. */
  100024. LayerSceneComponent.prototype.rebuild = function () {
  100025. var layers = this.scene.layers;
  100026. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  100027. var layer = layers_1[_i];
  100028. layer._rebuild();
  100029. }
  100030. };
  100031. /**
  100032. * Disposes the component and the associated ressources.
  100033. */
  100034. LayerSceneComponent.prototype.dispose = function () {
  100035. var layers = this.scene.layers;
  100036. while (layers.length) {
  100037. layers[0].dispose();
  100038. }
  100039. };
  100040. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  100041. var layers = this.scene.layers;
  100042. if (layers.length) {
  100043. this._engine.setDepthBuffer(false);
  100044. var cameraLayerMask = camera.layerMask;
  100045. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100046. var layer = layers_2[_i];
  100047. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  100048. layer.render();
  100049. }
  100050. }
  100051. this._engine.setDepthBuffer(true);
  100052. }
  100053. };
  100054. LayerSceneComponent.prototype._drawBackground = function (camera) {
  100055. this._draw(camera, true);
  100056. };
  100057. LayerSceneComponent.prototype._drawForeground = function (camera) {
  100058. this._draw(camera, false);
  100059. };
  100060. return LayerSceneComponent;
  100061. }());
  100062. BABYLON.LayerSceneComponent = LayerSceneComponent;
  100063. })(BABYLON || (BABYLON = {}));
  100064. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  100065. var BABYLON;
  100066. (function (BABYLON) {
  100067. var Layer = /** @class */ (function () {
  100068. function Layer(name, imgUrl, scene, isBackground, color) {
  100069. this.name = name;
  100070. this.scale = new BABYLON.Vector2(1, 1);
  100071. this.offset = new BABYLON.Vector2(0, 0);
  100072. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  100073. this.layerMask = 0x0FFFFFFF;
  100074. this._vertexBuffers = {};
  100075. // Events
  100076. /**
  100077. * An event triggered when the layer is disposed.
  100078. */
  100079. this.onDisposeObservable = new BABYLON.Observable();
  100080. /**
  100081. * An event triggered before rendering the scene
  100082. */
  100083. this.onBeforeRenderObservable = new BABYLON.Observable();
  100084. /**
  100085. * An event triggered after rendering the scene
  100086. */
  100087. this.onAfterRenderObservable = new BABYLON.Observable();
  100088. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  100089. this.isBackground = isBackground === undefined ? true : isBackground;
  100090. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  100091. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  100092. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  100093. if (!layerComponent) {
  100094. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  100095. this._scene._addComponent(layerComponent);
  100096. }
  100097. this._scene.layers.push(this);
  100098. var engine = this._scene.getEngine();
  100099. // VBO
  100100. var vertices = [];
  100101. vertices.push(1, 1);
  100102. vertices.push(-1, 1);
  100103. vertices.push(-1, -1);
  100104. vertices.push(1, -1);
  100105. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100106. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100107. this._createIndexBuffer();
  100108. // Effects
  100109. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  100110. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  100111. }
  100112. Object.defineProperty(Layer.prototype, "onDispose", {
  100113. set: function (callback) {
  100114. if (this._onDisposeObserver) {
  100115. this.onDisposeObservable.remove(this._onDisposeObserver);
  100116. }
  100117. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100118. },
  100119. enumerable: true,
  100120. configurable: true
  100121. });
  100122. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  100123. set: function (callback) {
  100124. if (this._onBeforeRenderObserver) {
  100125. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  100126. }
  100127. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  100128. },
  100129. enumerable: true,
  100130. configurable: true
  100131. });
  100132. Object.defineProperty(Layer.prototype, "onAfterRender", {
  100133. set: function (callback) {
  100134. if (this._onAfterRenderObserver) {
  100135. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100136. }
  100137. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  100138. },
  100139. enumerable: true,
  100140. configurable: true
  100141. });
  100142. Layer.prototype._createIndexBuffer = function () {
  100143. var engine = this._scene.getEngine();
  100144. // Indices
  100145. var indices = [];
  100146. indices.push(0);
  100147. indices.push(1);
  100148. indices.push(2);
  100149. indices.push(0);
  100150. indices.push(2);
  100151. indices.push(3);
  100152. this._indexBuffer = engine.createIndexBuffer(indices);
  100153. };
  100154. Layer.prototype._rebuild = function () {
  100155. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100156. if (vb) {
  100157. vb._rebuild();
  100158. }
  100159. this._createIndexBuffer();
  100160. };
  100161. Layer.prototype.render = function () {
  100162. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  100163. // Check
  100164. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  100165. return;
  100166. var engine = this._scene.getEngine();
  100167. this.onBeforeRenderObservable.notifyObservers(this);
  100168. // Render
  100169. engine.enableEffect(currentEffect);
  100170. engine.setState(false);
  100171. // Texture
  100172. currentEffect.setTexture("textureSampler", this.texture);
  100173. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  100174. // Color
  100175. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  100176. // Scale / offset
  100177. currentEffect.setVector2("offset", this.offset);
  100178. currentEffect.setVector2("scale", this.scale);
  100179. // VBOs
  100180. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100181. // Draw order
  100182. if (!this.alphaTest) {
  100183. engine.setAlphaMode(this.alphaBlendingMode);
  100184. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100185. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100186. }
  100187. else {
  100188. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100189. }
  100190. this.onAfterRenderObservable.notifyObservers(this);
  100191. };
  100192. Layer.prototype.dispose = function () {
  100193. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100194. if (vertexBuffer) {
  100195. vertexBuffer.dispose();
  100196. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100197. }
  100198. if (this._indexBuffer) {
  100199. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100200. this._indexBuffer = null;
  100201. }
  100202. if (this.texture) {
  100203. this.texture.dispose();
  100204. this.texture = null;
  100205. }
  100206. // Remove from scene
  100207. var index = this._scene.layers.indexOf(this);
  100208. this._scene.layers.splice(index, 1);
  100209. // Callback
  100210. this.onDisposeObservable.notifyObservers(this);
  100211. this.onDisposeObservable.clear();
  100212. this.onAfterRenderObservable.clear();
  100213. this.onBeforeRenderObservable.clear();
  100214. };
  100215. return Layer;
  100216. }());
  100217. BABYLON.Layer = Layer;
  100218. })(BABYLON || (BABYLON = {}));
  100219. //# sourceMappingURL=babylon.layer.js.map
  100220. var BABYLON;
  100221. (function (BABYLON) {
  100222. var TextureTools = /** @class */ (function () {
  100223. function TextureTools() {
  100224. }
  100225. /**
  100226. * Uses the GPU to create a copy texture rescaled at a given size
  100227. * @param texture Texture to copy from
  100228. * @param width Desired width
  100229. * @param height Desired height
  100230. * @return Generated texture
  100231. */
  100232. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  100233. if (useBilinearMode === void 0) { useBilinearMode = true; }
  100234. var scene = texture.getScene();
  100235. var engine = scene.getEngine();
  100236. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  100237. rtt.wrapU = texture.wrapU;
  100238. rtt.wrapV = texture.wrapV;
  100239. rtt.uOffset = texture.uOffset;
  100240. rtt.vOffset = texture.vOffset;
  100241. rtt.uScale = texture.uScale;
  100242. rtt.vScale = texture.vScale;
  100243. rtt.uAng = texture.uAng;
  100244. rtt.vAng = texture.vAng;
  100245. rtt.wAng = texture.wAng;
  100246. rtt.coordinatesIndex = texture.coordinatesIndex;
  100247. rtt.level = texture.level;
  100248. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  100249. rtt._texture.isReady = false;
  100250. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100251. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100252. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100253. passPostProcess.getEffect().executeWhenCompiled(function () {
  100254. passPostProcess.onApply = function (effect) {
  100255. effect.setTexture("textureSampler", texture);
  100256. };
  100257. var internalTexture = rtt.getInternalTexture();
  100258. if (internalTexture) {
  100259. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  100260. engine.unBindFramebuffer(internalTexture);
  100261. rtt.disposeFramebufferObjects();
  100262. passPostProcess.dispose();
  100263. internalTexture.isReady = true;
  100264. }
  100265. });
  100266. return rtt;
  100267. };
  100268. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  100269. if (!scene._environmentBRDFTexture) {
  100270. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100271. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100272. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100273. scene._environmentBRDFTexture = texture;
  100274. }
  100275. return scene._environmentBRDFTexture;
  100276. };
  100277. 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=";
  100278. return TextureTools;
  100279. }());
  100280. BABYLON.TextureTools = TextureTools;
  100281. })(BABYLON || (BABYLON = {}));
  100282. //# sourceMappingURL=babylon.textureTools.js.map
  100283. var BABYLON;
  100284. (function (BABYLON) {
  100285. var FramingBehavior = /** @class */ (function () {
  100286. function FramingBehavior() {
  100287. this._mode = FramingBehavior.FitFrustumSidesMode;
  100288. this._radiusScale = 1.0;
  100289. this._positionScale = 0.5;
  100290. this._defaultElevation = 0.3;
  100291. this._elevationReturnTime = 1500;
  100292. this._elevationReturnWaitTime = 1000;
  100293. this._zoomStopsAnimation = false;
  100294. this._framingTime = 1500;
  100295. this._isPointerDown = false;
  100296. this._lastInteractionTime = -Infinity;
  100297. // Framing control
  100298. this._animatables = new Array();
  100299. this._betaIsAnimating = false;
  100300. }
  100301. Object.defineProperty(FramingBehavior.prototype, "name", {
  100302. get: function () {
  100303. return "Framing";
  100304. },
  100305. enumerable: true,
  100306. configurable: true
  100307. });
  100308. Object.defineProperty(FramingBehavior.prototype, "mode", {
  100309. /**
  100310. * Gets current mode used by the behavior.
  100311. */
  100312. get: function () {
  100313. return this._mode;
  100314. },
  100315. /**
  100316. * Sets the current mode used by the behavior
  100317. */
  100318. set: function (mode) {
  100319. this._mode = mode;
  100320. },
  100321. enumerable: true,
  100322. configurable: true
  100323. });
  100324. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  100325. /**
  100326. * Gets the scale applied to the radius
  100327. */
  100328. get: function () {
  100329. return this._radiusScale;
  100330. },
  100331. /**
  100332. * Sets the scale applied to the radius (1 by default)
  100333. */
  100334. set: function (radius) {
  100335. this._radiusScale = radius;
  100336. },
  100337. enumerable: true,
  100338. configurable: true
  100339. });
  100340. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  100341. /**
  100342. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100343. */
  100344. get: function () {
  100345. return this._positionScale;
  100346. },
  100347. /**
  100348. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100349. */
  100350. set: function (scale) {
  100351. this._positionScale = scale;
  100352. },
  100353. enumerable: true,
  100354. configurable: true
  100355. });
  100356. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  100357. /**
  100358. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100359. * behaviour is triggered, in radians.
  100360. */
  100361. get: function () {
  100362. return this._defaultElevation;
  100363. },
  100364. /**
  100365. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100366. * behaviour is triggered, in radians.
  100367. */
  100368. set: function (elevation) {
  100369. this._defaultElevation = elevation;
  100370. },
  100371. enumerable: true,
  100372. configurable: true
  100373. });
  100374. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  100375. /**
  100376. * Gets the time (in milliseconds) taken to return to the default beta position.
  100377. * Negative value indicates camera should not return to default.
  100378. */
  100379. get: function () {
  100380. return this._elevationReturnTime;
  100381. },
  100382. /**
  100383. * Sets the time (in milliseconds) taken to return to the default beta position.
  100384. * Negative value indicates camera should not return to default.
  100385. */
  100386. set: function (speed) {
  100387. this._elevationReturnTime = speed;
  100388. },
  100389. enumerable: true,
  100390. configurable: true
  100391. });
  100392. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  100393. /**
  100394. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100395. */
  100396. get: function () {
  100397. return this._elevationReturnWaitTime;
  100398. },
  100399. /**
  100400. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100401. */
  100402. set: function (time) {
  100403. this._elevationReturnWaitTime = time;
  100404. },
  100405. enumerable: true,
  100406. configurable: true
  100407. });
  100408. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  100409. /**
  100410. * Gets the flag that indicates if user zooming should stop animation.
  100411. */
  100412. get: function () {
  100413. return this._zoomStopsAnimation;
  100414. },
  100415. /**
  100416. * Sets the flag that indicates if user zooming should stop animation.
  100417. */
  100418. set: function (flag) {
  100419. this._zoomStopsAnimation = flag;
  100420. },
  100421. enumerable: true,
  100422. configurable: true
  100423. });
  100424. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  100425. /**
  100426. * Gets the transition time when framing the mesh, in milliseconds
  100427. */
  100428. get: function () {
  100429. return this._framingTime;
  100430. },
  100431. /**
  100432. * Sets the transition time when framing the mesh, in milliseconds
  100433. */
  100434. set: function (time) {
  100435. this._framingTime = time;
  100436. },
  100437. enumerable: true,
  100438. configurable: true
  100439. });
  100440. FramingBehavior.prototype.init = function () {
  100441. // Do notihng
  100442. };
  100443. FramingBehavior.prototype.attach = function (camera) {
  100444. var _this = this;
  100445. this._attachedCamera = camera;
  100446. var scene = this._attachedCamera.getScene();
  100447. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  100448. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100449. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100450. _this._isPointerDown = true;
  100451. return;
  100452. }
  100453. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100454. _this._isPointerDown = false;
  100455. }
  100456. });
  100457. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100458. if (mesh) {
  100459. _this.zoomOnMesh(mesh);
  100460. }
  100461. });
  100462. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100463. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100464. _this._applyUserInteraction();
  100465. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  100466. // back to the default position after a given timeout
  100467. _this._maintainCameraAboveGround();
  100468. });
  100469. };
  100470. FramingBehavior.prototype.detach = function () {
  100471. if (!this._attachedCamera) {
  100472. return;
  100473. }
  100474. var scene = this._attachedCamera.getScene();
  100475. if (this._onPrePointerObservableObserver) {
  100476. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100477. }
  100478. if (this._onAfterCheckInputsObserver) {
  100479. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100480. }
  100481. if (this._onMeshTargetChangedObserver) {
  100482. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100483. }
  100484. this._attachedCamera = null;
  100485. };
  100486. /**
  100487. * Targets the given mesh and updates zoom level accordingly.
  100488. * @param mesh The mesh to target.
  100489. * @param radius Optional. If a cached radius position already exists, overrides default.
  100490. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100491. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100492. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100493. */
  100494. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100495. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100496. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100497. mesh.computeWorldMatrix(true);
  100498. var boundingBox = mesh.getBoundingInfo().boundingBox;
  100499. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  100500. };
  100501. /**
  100502. * Targets the given mesh with its children and updates zoom level accordingly.
  100503. * @param mesh The mesh to target.
  100504. * @param radius Optional. If a cached radius position already exists, overrides default.
  100505. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100506. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100507. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100508. */
  100509. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100510. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100511. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100512. mesh.computeWorldMatrix(true);
  100513. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  100514. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  100515. };
  100516. /**
  100517. * Targets the given meshes with their children and updates zoom level accordingly.
  100518. * @param meshes The mesh to target.
  100519. * @param radius Optional. If a cached radius position already exists, overrides default.
  100520. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100521. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100522. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100523. */
  100524. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  100525. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100526. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100527. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  100528. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  100529. for (var i = 0; i < meshes.length; i++) {
  100530. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  100531. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  100532. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  100533. }
  100534. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  100535. };
  100536. /**
  100537. * Targets the given mesh and updates zoom level accordingly.
  100538. * @param mesh The mesh to target.
  100539. * @param radius Optional. If a cached radius position already exists, overrides default.
  100540. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100541. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100542. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100543. */
  100544. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  100545. var _this = this;
  100546. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100547. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100548. var zoomTarget;
  100549. if (!this._attachedCamera) {
  100550. return;
  100551. }
  100552. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  100553. var bottom = minimumWorld.y;
  100554. var top = maximumWorld.y;
  100555. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  100556. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  100557. if (focusOnOriginXZ) {
  100558. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  100559. }
  100560. else {
  100561. var centerWorld = minimumWorld.add(radiusWorld);
  100562. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  100563. }
  100564. if (!this._vectorTransition) {
  100565. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  100566. }
  100567. this._betaIsAnimating = true;
  100568. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  100569. if (animatable) {
  100570. this._animatables.push(animatable);
  100571. }
  100572. // sets the radius and lower radius bounds
  100573. // Small delta ensures camera is not always at lower zoom limit.
  100574. var radius = 0;
  100575. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  100576. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100577. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  100578. radius = position;
  100579. }
  100580. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100581. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100582. if (this._attachedCamera.lowerRadiusLimit === null) {
  100583. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  100584. }
  100585. }
  100586. // Set sensibilities
  100587. var extend = maximumWorld.subtract(minimumWorld).length();
  100588. this._attachedCamera.panningSensibility = 5000 / extend;
  100589. this._attachedCamera.wheelPrecision = 100 / radius;
  100590. // transition to new radius
  100591. if (!this._radiusTransition) {
  100592. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100593. }
  100594. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  100595. _this.stopAllAnimations();
  100596. if (onAnimationEnd) {
  100597. onAnimationEnd();
  100598. }
  100599. if (_this._attachedCamera) {
  100600. _this._attachedCamera.storeState();
  100601. }
  100602. });
  100603. if (animatable) {
  100604. this._animatables.push(animatable);
  100605. }
  100606. };
  100607. /**
  100608. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  100609. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  100610. * frustum width.
  100611. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  100612. * to fully enclose the mesh in the viewing frustum.
  100613. */
  100614. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  100615. var size = maximumWorld.subtract(minimumWorld);
  100616. var boxVectorGlobalDiagonal = size.length();
  100617. var frustumSlope = this._getFrustumSlope();
  100618. // Formula for setting distance
  100619. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  100620. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  100621. // Horizon distance
  100622. var radius = radiusWithoutFraming * this._radiusScale;
  100623. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  100624. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  100625. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  100626. var camera = this._attachedCamera;
  100627. if (!camera) {
  100628. return 0;
  100629. }
  100630. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100631. // Don't exceed the requested limit
  100632. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  100633. }
  100634. // Don't exceed the upper radius limit
  100635. if (camera.upperRadiusLimit) {
  100636. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  100637. }
  100638. return distance;
  100639. };
  100640. /**
  100641. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  100642. * is automatically returned to its default position (expected to be above ground plane).
  100643. */
  100644. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  100645. var _this = this;
  100646. if (this._elevationReturnTime < 0) {
  100647. return;
  100648. }
  100649. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  100650. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  100651. var limitBeta = Math.PI * 0.5;
  100652. // Bring the camera back up if below the ground plane
  100653. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  100654. this._betaIsAnimating = true;
  100655. //Transition to new position
  100656. this.stopAllAnimations();
  100657. if (!this._betaTransition) {
  100658. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100659. }
  100660. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  100661. _this._clearAnimationLocks();
  100662. _this.stopAllAnimations();
  100663. });
  100664. if (animatabe) {
  100665. this._animatables.push(animatabe);
  100666. }
  100667. }
  100668. };
  100669. /**
  100670. * Returns the frustum slope based on the canvas ratio and camera FOV
  100671. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  100672. */
  100673. FramingBehavior.prototype._getFrustumSlope = function () {
  100674. // Calculate the viewport ratio
  100675. // Aspect Ratio is Height/Width.
  100676. var camera = this._attachedCamera;
  100677. if (!camera) {
  100678. return BABYLON.Vector2.Zero();
  100679. }
  100680. var engine = camera.getScene().getEngine();
  100681. var aspectRatio = engine.getAspectRatio(camera);
  100682. // Camera FOV is the vertical field of view (top-bottom) in radians.
  100683. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  100684. var frustumSlopeY = Math.tan(camera.fov / 2);
  100685. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  100686. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  100687. // along the forward vector.
  100688. var frustumSlopeX = frustumSlopeY * aspectRatio;
  100689. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  100690. };
  100691. /**
  100692. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  100693. */
  100694. FramingBehavior.prototype._clearAnimationLocks = function () {
  100695. this._betaIsAnimating = false;
  100696. };
  100697. /**
  100698. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100699. */
  100700. FramingBehavior.prototype._applyUserInteraction = function () {
  100701. if (this.isUserIsMoving) {
  100702. this._lastInteractionTime = BABYLON.Tools.Now;
  100703. this.stopAllAnimations();
  100704. this._clearAnimationLocks();
  100705. }
  100706. };
  100707. /**
  100708. * Stops and removes all animations that have been applied to the camera
  100709. */
  100710. FramingBehavior.prototype.stopAllAnimations = function () {
  100711. if (this._attachedCamera) {
  100712. this._attachedCamera.animations = [];
  100713. }
  100714. while (this._animatables.length) {
  100715. if (this._animatables[0]) {
  100716. this._animatables[0].onAnimationEnd = null;
  100717. this._animatables[0].stop();
  100718. }
  100719. this._animatables.shift();
  100720. }
  100721. };
  100722. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  100723. /**
  100724. * Gets a value indicating if the user is moving the camera
  100725. */
  100726. get: function () {
  100727. if (!this._attachedCamera) {
  100728. return false;
  100729. }
  100730. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100731. this._attachedCamera.inertialBetaOffset !== 0 ||
  100732. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100733. this._attachedCamera.inertialPanningX !== 0 ||
  100734. this._attachedCamera.inertialPanningY !== 0 ||
  100735. this._isPointerDown;
  100736. },
  100737. enumerable: true,
  100738. configurable: true
  100739. });
  100740. /**
  100741. * The easing function used by animations
  100742. */
  100743. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  100744. /**
  100745. * The easing mode used by animations
  100746. */
  100747. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  100748. // Statics
  100749. /**
  100750. * The camera can move all the way towards the mesh.
  100751. */
  100752. FramingBehavior.IgnoreBoundsSizeMode = 0;
  100753. /**
  100754. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  100755. */
  100756. FramingBehavior.FitFrustumSidesMode = 1;
  100757. return FramingBehavior;
  100758. }());
  100759. BABYLON.FramingBehavior = FramingBehavior;
  100760. })(BABYLON || (BABYLON = {}));
  100761. //# sourceMappingURL=babylon.framingBehavior.js.map
  100762. var BABYLON;
  100763. (function (BABYLON) {
  100764. /**
  100765. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  100766. */
  100767. var BouncingBehavior = /** @class */ (function () {
  100768. function BouncingBehavior() {
  100769. /**
  100770. * The duration of the animation, in milliseconds
  100771. */
  100772. this.transitionDuration = 450;
  100773. /**
  100774. * Length of the distance animated by the transition when lower radius is reached
  100775. */
  100776. this.lowerRadiusTransitionRange = 2;
  100777. /**
  100778. * Length of the distance animated by the transition when upper radius is reached
  100779. */
  100780. this.upperRadiusTransitionRange = -2;
  100781. this._autoTransitionRange = false;
  100782. // Animations
  100783. this._radiusIsAnimating = false;
  100784. this._radiusBounceTransition = null;
  100785. this._animatables = new Array();
  100786. }
  100787. Object.defineProperty(BouncingBehavior.prototype, "name", {
  100788. get: function () {
  100789. return "Bouncing";
  100790. },
  100791. enumerable: true,
  100792. configurable: true
  100793. });
  100794. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  100795. /**
  100796. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100797. */
  100798. get: function () {
  100799. return this._autoTransitionRange;
  100800. },
  100801. /**
  100802. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100803. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  100804. */
  100805. set: function (value) {
  100806. var _this = this;
  100807. if (this._autoTransitionRange === value) {
  100808. return;
  100809. }
  100810. this._autoTransitionRange = value;
  100811. var camera = this._attachedCamera;
  100812. if (!camera) {
  100813. return;
  100814. }
  100815. if (value) {
  100816. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100817. if (!mesh) {
  100818. return;
  100819. }
  100820. mesh.computeWorldMatrix(true);
  100821. var diagonal = mesh.getBoundingInfo().diagonalLength;
  100822. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  100823. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100824. });
  100825. }
  100826. else if (this._onMeshTargetChangedObserver) {
  100827. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100828. }
  100829. },
  100830. enumerable: true,
  100831. configurable: true
  100832. });
  100833. BouncingBehavior.prototype.init = function () {
  100834. // Do notihng
  100835. };
  100836. BouncingBehavior.prototype.attach = function (camera) {
  100837. var _this = this;
  100838. this._attachedCamera = camera;
  100839. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100840. if (!_this._attachedCamera) {
  100841. return;
  100842. }
  100843. // Add the bounce animation to the lower radius limit
  100844. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100845. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100846. }
  100847. // Add the bounce animation to the upper radius limit
  100848. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100849. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100850. }
  100851. });
  100852. };
  100853. BouncingBehavior.prototype.detach = function () {
  100854. if (!this._attachedCamera) {
  100855. return;
  100856. }
  100857. if (this._onAfterCheckInputsObserver) {
  100858. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100859. }
  100860. if (this._onMeshTargetChangedObserver) {
  100861. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100862. }
  100863. this._attachedCamera = null;
  100864. };
  100865. /**
  100866. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100867. * @param radiusLimit The limit to check against.
  100868. * @return Bool to indicate if at limit.
  100869. */
  100870. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100871. if (!this._attachedCamera) {
  100872. return false;
  100873. }
  100874. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100875. return true;
  100876. }
  100877. return false;
  100878. };
  100879. /**
  100880. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100881. * @param radiusDelta The delta by which to animate to. Can be negative.
  100882. */
  100883. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100884. var _this = this;
  100885. if (!this._attachedCamera) {
  100886. return;
  100887. }
  100888. if (!this._radiusBounceTransition) {
  100889. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100890. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100891. }
  100892. // Prevent zoom until bounce has completed
  100893. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100894. this._attachedCamera.wheelPrecision = Infinity;
  100895. this._attachedCamera.inertialRadiusOffset = 0;
  100896. // Animate to the radius limit
  100897. this.stopAllAnimations();
  100898. this._radiusIsAnimating = true;
  100899. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100900. if (animatable) {
  100901. this._animatables.push(animatable);
  100902. }
  100903. };
  100904. /**
  100905. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100906. */
  100907. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100908. this._radiusIsAnimating = false;
  100909. if (this._attachedCamera) {
  100910. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100911. }
  100912. };
  100913. /**
  100914. * Stops and removes all animations that have been applied to the camera
  100915. */
  100916. BouncingBehavior.prototype.stopAllAnimations = function () {
  100917. if (this._attachedCamera) {
  100918. this._attachedCamera.animations = [];
  100919. }
  100920. while (this._animatables.length) {
  100921. this._animatables[0].onAnimationEnd = null;
  100922. this._animatables[0].stop();
  100923. this._animatables.shift();
  100924. }
  100925. };
  100926. /**
  100927. * The easing function used by animations
  100928. */
  100929. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100930. /**
  100931. * The easing mode used by animations
  100932. */
  100933. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100934. return BouncingBehavior;
  100935. }());
  100936. BABYLON.BouncingBehavior = BouncingBehavior;
  100937. })(BABYLON || (BABYLON = {}));
  100938. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100939. var BABYLON;
  100940. (function (BABYLON) {
  100941. var AutoRotationBehavior = /** @class */ (function () {
  100942. function AutoRotationBehavior() {
  100943. this._zoomStopsAnimation = false;
  100944. this._idleRotationSpeed = 0.05;
  100945. this._idleRotationWaitTime = 2000;
  100946. this._idleRotationSpinupTime = 2000;
  100947. this._isPointerDown = false;
  100948. this._lastFrameTime = null;
  100949. this._lastInteractionTime = -Infinity;
  100950. this._cameraRotationSpeed = 0;
  100951. this._lastFrameRadius = 0;
  100952. }
  100953. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100954. get: function () {
  100955. return "AutoRotation";
  100956. },
  100957. enumerable: true,
  100958. configurable: true
  100959. });
  100960. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100961. /**
  100962. * Gets the flag that indicates if user zooming should stop animation.
  100963. */
  100964. get: function () {
  100965. return this._zoomStopsAnimation;
  100966. },
  100967. /**
  100968. * Sets the flag that indicates if user zooming should stop animation.
  100969. */
  100970. set: function (flag) {
  100971. this._zoomStopsAnimation = flag;
  100972. },
  100973. enumerable: true,
  100974. configurable: true
  100975. });
  100976. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100977. /**
  100978. * Gets the default speed at which the camera rotates around the model.
  100979. */
  100980. get: function () {
  100981. return this._idleRotationSpeed;
  100982. },
  100983. /**
  100984. * Sets the default speed at which the camera rotates around the model.
  100985. */
  100986. set: function (speed) {
  100987. this._idleRotationSpeed = speed;
  100988. },
  100989. enumerable: true,
  100990. configurable: true
  100991. });
  100992. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100993. /**
  100994. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100995. */
  100996. get: function () {
  100997. return this._idleRotationWaitTime;
  100998. },
  100999. /**
  101000. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  101001. */
  101002. set: function (time) {
  101003. this._idleRotationWaitTime = time;
  101004. },
  101005. enumerable: true,
  101006. configurable: true
  101007. });
  101008. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  101009. /**
  101010. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101011. */
  101012. get: function () {
  101013. return this._idleRotationSpinupTime;
  101014. },
  101015. /**
  101016. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101017. */
  101018. set: function (time) {
  101019. this._idleRotationSpinupTime = time;
  101020. },
  101021. enumerable: true,
  101022. configurable: true
  101023. });
  101024. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  101025. /**
  101026. * Gets a value indicating if the camera is currently rotating because of this behavior
  101027. */
  101028. get: function () {
  101029. return Math.abs(this._cameraRotationSpeed) > 0;
  101030. },
  101031. enumerable: true,
  101032. configurable: true
  101033. });
  101034. AutoRotationBehavior.prototype.init = function () {
  101035. // Do notihng
  101036. };
  101037. AutoRotationBehavior.prototype.attach = function (camera) {
  101038. var _this = this;
  101039. this._attachedCamera = camera;
  101040. var scene = this._attachedCamera.getScene();
  101041. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101042. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101043. _this._isPointerDown = true;
  101044. return;
  101045. }
  101046. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101047. _this._isPointerDown = false;
  101048. }
  101049. });
  101050. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101051. var now = BABYLON.Tools.Now;
  101052. var dt = 0;
  101053. if (_this._lastFrameTime != null) {
  101054. dt = now - _this._lastFrameTime;
  101055. }
  101056. _this._lastFrameTime = now;
  101057. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101058. _this._applyUserInteraction();
  101059. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  101060. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  101061. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  101062. // Step camera rotation by rotation speed
  101063. if (_this._attachedCamera) {
  101064. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  101065. }
  101066. });
  101067. };
  101068. AutoRotationBehavior.prototype.detach = function () {
  101069. if (!this._attachedCamera) {
  101070. return;
  101071. }
  101072. var scene = this._attachedCamera.getScene();
  101073. if (this._onPrePointerObservableObserver) {
  101074. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101075. }
  101076. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101077. this._attachedCamera = null;
  101078. };
  101079. /**
  101080. * Returns true if user is scrolling.
  101081. * @return true if user is scrolling.
  101082. */
  101083. AutoRotationBehavior.prototype._userIsZooming = function () {
  101084. if (!this._attachedCamera) {
  101085. return false;
  101086. }
  101087. return this._attachedCamera.inertialRadiusOffset !== 0;
  101088. };
  101089. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  101090. if (!this._attachedCamera) {
  101091. return false;
  101092. }
  101093. var zoomHasHitLimit = false;
  101094. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  101095. zoomHasHitLimit = true;
  101096. }
  101097. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  101098. this._lastFrameRadius = this._attachedCamera.radius;
  101099. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  101100. };
  101101. /**
  101102. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101103. */
  101104. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  101105. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  101106. this._lastInteractionTime = BABYLON.Tools.Now;
  101107. }
  101108. };
  101109. // Tools
  101110. AutoRotationBehavior.prototype._userIsMoving = function () {
  101111. if (!this._attachedCamera) {
  101112. return false;
  101113. }
  101114. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101115. this._attachedCamera.inertialBetaOffset !== 0 ||
  101116. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101117. this._attachedCamera.inertialPanningX !== 0 ||
  101118. this._attachedCamera.inertialPanningY !== 0 ||
  101119. this._isPointerDown;
  101120. };
  101121. return AutoRotationBehavior;
  101122. }());
  101123. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  101124. })(BABYLON || (BABYLON = {}));
  101125. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  101126. var BABYLON;
  101127. (function (BABYLON) {
  101128. var NullEngineOptions = /** @class */ (function () {
  101129. function NullEngineOptions() {
  101130. this.renderWidth = 512;
  101131. this.renderHeight = 256;
  101132. this.textureSize = 512;
  101133. this.deterministicLockstep = false;
  101134. this.lockstepMaxSteps = 4;
  101135. }
  101136. return NullEngineOptions;
  101137. }());
  101138. BABYLON.NullEngineOptions = NullEngineOptions;
  101139. /**
  101140. * The null engine class provides support for headless version of babylon.js.
  101141. * This can be used in server side scenario or for testing purposes
  101142. */
  101143. var NullEngine = /** @class */ (function (_super) {
  101144. __extends(NullEngine, _super);
  101145. function NullEngine(options) {
  101146. if (options === void 0) { options = new NullEngineOptions(); }
  101147. var _this = _super.call(this, null) || this;
  101148. if (options.deterministicLockstep === undefined) {
  101149. options.deterministicLockstep = false;
  101150. }
  101151. if (options.lockstepMaxSteps === undefined) {
  101152. options.lockstepMaxSteps = 4;
  101153. }
  101154. _this._options = options;
  101155. // Init caps
  101156. // We consider we are on a webgl1 capable device
  101157. _this._caps = new BABYLON.EngineCapabilities();
  101158. _this._caps.maxTexturesImageUnits = 16;
  101159. _this._caps.maxVertexTextureImageUnits = 16;
  101160. _this._caps.maxTextureSize = 512;
  101161. _this._caps.maxCubemapTextureSize = 512;
  101162. _this._caps.maxRenderTextureSize = 512;
  101163. _this._caps.maxVertexAttribs = 16;
  101164. _this._caps.maxVaryingVectors = 16;
  101165. _this._caps.maxFragmentUniformVectors = 16;
  101166. _this._caps.maxVertexUniformVectors = 16;
  101167. // Extensions
  101168. _this._caps.standardDerivatives = false;
  101169. _this._caps.astc = null;
  101170. _this._caps.s3tc = null;
  101171. _this._caps.pvrtc = null;
  101172. _this._caps.etc1 = null;
  101173. _this._caps.etc2 = null;
  101174. _this._caps.textureAnisotropicFilterExtension = null;
  101175. _this._caps.maxAnisotropy = 0;
  101176. _this._caps.uintIndices = false;
  101177. _this._caps.fragmentDepthSupported = false;
  101178. _this._caps.highPrecisionShaderSupported = true;
  101179. _this._caps.colorBufferFloat = false;
  101180. _this._caps.textureFloat = false;
  101181. _this._caps.textureFloatLinearFiltering = false;
  101182. _this._caps.textureFloatRender = false;
  101183. _this._caps.textureHalfFloat = false;
  101184. _this._caps.textureHalfFloatLinearFiltering = false;
  101185. _this._caps.textureHalfFloatRender = false;
  101186. _this._caps.textureLOD = false;
  101187. _this._caps.drawBuffersExtension = false;
  101188. _this._caps.depthTextureExtension = false;
  101189. _this._caps.vertexArrayObject = false;
  101190. _this._caps.instancedArrays = false;
  101191. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  101192. // Wrappers
  101193. if (typeof URL === "undefined") {
  101194. URL = {
  101195. createObjectURL: function () { },
  101196. revokeObjectURL: function () { }
  101197. };
  101198. }
  101199. if (typeof Blob === "undefined") {
  101200. Blob = function () { };
  101201. }
  101202. return _this;
  101203. }
  101204. NullEngine.prototype.isDeterministicLockStep = function () {
  101205. return this._options.deterministicLockstep;
  101206. };
  101207. NullEngine.prototype.getLockstepMaxSteps = function () {
  101208. return this._options.lockstepMaxSteps;
  101209. };
  101210. NullEngine.prototype.getHardwareScalingLevel = function () {
  101211. return 1.0;
  101212. };
  101213. NullEngine.prototype.createVertexBuffer = function (vertices) {
  101214. return {
  101215. capacity: 0,
  101216. references: 1,
  101217. is32Bits: false
  101218. };
  101219. };
  101220. NullEngine.prototype.createIndexBuffer = function (indices) {
  101221. return {
  101222. capacity: 0,
  101223. references: 1,
  101224. is32Bits: false
  101225. };
  101226. };
  101227. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  101228. if (stencil === void 0) { stencil = false; }
  101229. };
  101230. NullEngine.prototype.getRenderWidth = function (useScreen) {
  101231. if (useScreen === void 0) { useScreen = false; }
  101232. if (!useScreen && this._currentRenderTarget) {
  101233. return this._currentRenderTarget.width;
  101234. }
  101235. return this._options.renderWidth;
  101236. };
  101237. NullEngine.prototype.getRenderHeight = function (useScreen) {
  101238. if (useScreen === void 0) { useScreen = false; }
  101239. if (!useScreen && this._currentRenderTarget) {
  101240. return this._currentRenderTarget.height;
  101241. }
  101242. return this._options.renderHeight;
  101243. };
  101244. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  101245. this._cachedViewport = viewport;
  101246. };
  101247. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  101248. return {
  101249. transformFeedback: null,
  101250. __SPECTOR_rebuildProgram: null
  101251. };
  101252. };
  101253. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  101254. return [];
  101255. };
  101256. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  101257. return [];
  101258. };
  101259. NullEngine.prototype.bindSamplers = function (effect) {
  101260. this._currentEffect = null;
  101261. };
  101262. NullEngine.prototype.enableEffect = function (effect) {
  101263. this._currentEffect = effect;
  101264. if (effect.onBind) {
  101265. effect.onBind(effect);
  101266. }
  101267. effect.onBindObservable.notifyObservers(effect);
  101268. };
  101269. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  101270. if (zOffset === void 0) { zOffset = 0; }
  101271. if (reverseSide === void 0) { reverseSide = false; }
  101272. };
  101273. NullEngine.prototype.setIntArray = function (uniform, array) {
  101274. };
  101275. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  101276. };
  101277. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  101278. };
  101279. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  101280. };
  101281. NullEngine.prototype.setFloatArray = function (uniform, array) {
  101282. };
  101283. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  101284. };
  101285. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  101286. };
  101287. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  101288. };
  101289. NullEngine.prototype.setArray = function (uniform, array) {
  101290. };
  101291. NullEngine.prototype.setArray2 = function (uniform, array) {
  101292. };
  101293. NullEngine.prototype.setArray3 = function (uniform, array) {
  101294. };
  101295. NullEngine.prototype.setArray4 = function (uniform, array) {
  101296. };
  101297. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  101298. };
  101299. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  101300. };
  101301. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  101302. };
  101303. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  101304. };
  101305. NullEngine.prototype.setFloat = function (uniform, value) {
  101306. };
  101307. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  101308. };
  101309. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  101310. };
  101311. NullEngine.prototype.setBool = function (uniform, bool) {
  101312. };
  101313. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  101314. };
  101315. NullEngine.prototype.setColor3 = function (uniform, color3) {
  101316. };
  101317. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  101318. };
  101319. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  101320. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  101321. if (this._alphaMode === mode) {
  101322. return;
  101323. }
  101324. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  101325. if (!noDepthWriteChange) {
  101326. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  101327. }
  101328. this._alphaMode = mode;
  101329. };
  101330. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  101331. };
  101332. NullEngine.prototype.wipeCaches = function (bruteForce) {
  101333. if (this.preventCacheWipeBetweenFrames) {
  101334. return;
  101335. }
  101336. this.resetTextureCache();
  101337. this._currentEffect = null;
  101338. if (bruteForce) {
  101339. this._currentProgram = null;
  101340. this._stencilState.reset();
  101341. this._depthCullingState.reset();
  101342. this._alphaState.reset();
  101343. }
  101344. this._cachedVertexBuffers = null;
  101345. this._cachedIndexBuffer = null;
  101346. this._cachedEffectForVertexBuffers = null;
  101347. };
  101348. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  101349. };
  101350. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  101351. };
  101352. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  101353. };
  101354. NullEngine.prototype._createTexture = function () {
  101355. return {};
  101356. };
  101357. NullEngine.prototype._releaseTexture = function (texture) {
  101358. };
  101359. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  101360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101361. if (onLoad === void 0) { onLoad = null; }
  101362. if (onError === void 0) { onError = null; }
  101363. if (buffer === void 0) { buffer = null; }
  101364. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  101365. var url = String(urlArg);
  101366. texture.url = url;
  101367. texture.generateMipMaps = !noMipmap;
  101368. texture.samplingMode = samplingMode;
  101369. texture.invertY = invertY;
  101370. texture.baseWidth = this._options.textureSize;
  101371. texture.baseHeight = this._options.textureSize;
  101372. texture.width = this._options.textureSize;
  101373. texture.height = this._options.textureSize;
  101374. if (format) {
  101375. texture.format = format;
  101376. }
  101377. texture.isReady = true;
  101378. if (onLoad) {
  101379. onLoad();
  101380. }
  101381. this._internalTexturesCache.push(texture);
  101382. return texture;
  101383. };
  101384. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  101385. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  101386. if (options !== undefined && typeof options === "object") {
  101387. fullOptions.generateMipMaps = options.generateMipMaps;
  101388. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  101389. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  101390. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  101391. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  101392. }
  101393. else {
  101394. fullOptions.generateMipMaps = options;
  101395. fullOptions.generateDepthBuffer = true;
  101396. fullOptions.generateStencilBuffer = false;
  101397. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101398. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  101399. }
  101400. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  101401. var width = size.width || size;
  101402. var height = size.height || size;
  101403. texture._depthStencilBuffer = {};
  101404. texture._framebuffer = {};
  101405. texture.baseWidth = width;
  101406. texture.baseHeight = height;
  101407. texture.width = width;
  101408. texture.height = height;
  101409. texture.isReady = true;
  101410. texture.samples = 1;
  101411. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  101412. texture.samplingMode = fullOptions.samplingMode;
  101413. texture.type = fullOptions.type;
  101414. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  101415. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  101416. this._internalTexturesCache.push(texture);
  101417. return texture;
  101418. };
  101419. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  101420. texture.samplingMode = samplingMode;
  101421. };
  101422. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  101423. if (this._currentRenderTarget) {
  101424. this.unBindFramebuffer(this._currentRenderTarget);
  101425. }
  101426. this._currentRenderTarget = texture;
  101427. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  101428. if (this._cachedViewport && !forceFullscreenViewport) {
  101429. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  101430. }
  101431. };
  101432. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  101433. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  101434. this._currentRenderTarget = null;
  101435. if (onBeforeUnbind) {
  101436. if (texture._MSAAFramebuffer) {
  101437. this._currentFramebuffer = texture._framebuffer;
  101438. }
  101439. onBeforeUnbind();
  101440. }
  101441. this._currentFramebuffer = null;
  101442. };
  101443. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  101444. var vbo = {
  101445. capacity: 1,
  101446. references: 1,
  101447. is32Bits: false
  101448. };
  101449. return vbo;
  101450. };
  101451. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  101452. if (premulAlpha === void 0) { premulAlpha = false; }
  101453. };
  101454. /**
  101455. * Get the current error code of the webGL context
  101456. * @returns the error code
  101457. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  101458. */
  101459. NullEngine.prototype.getError = function () {
  101460. return 0;
  101461. };
  101462. /** @hidden */
  101463. NullEngine.prototype._getUnpackAlignement = function () {
  101464. return 1;
  101465. };
  101466. /** @hidden */
  101467. NullEngine.prototype._unpackFlipY = function (value) {
  101468. };
  101469. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  101470. if (offset === void 0) { offset = 0; }
  101471. };
  101472. /**
  101473. * Updates a dynamic vertex buffer.
  101474. * @param vertexBuffer the vertex buffer to update
  101475. * @param data the data used to update the vertex buffer
  101476. * @param byteOffset the byte offset of the data (optional)
  101477. * @param byteLength the byte length of the data (optional)
  101478. */
  101479. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  101480. };
  101481. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  101482. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  101483. this._boundTexturesCache[this._activeChannel] = texture;
  101484. return true;
  101485. }
  101486. return false;
  101487. };
  101488. NullEngine.prototype._bindTexture = function (channel, texture) {
  101489. if (channel < 0) {
  101490. return;
  101491. }
  101492. this._bindTextureDirectly(0, texture);
  101493. };
  101494. NullEngine.prototype._releaseBuffer = function (buffer) {
  101495. buffer.references--;
  101496. if (buffer.references === 0) {
  101497. return true;
  101498. }
  101499. return false;
  101500. };
  101501. NullEngine.prototype.releaseEffects = function () {
  101502. };
  101503. NullEngine.prototype.displayLoadingUI = function () {
  101504. };
  101505. NullEngine.prototype.hideLoadingUI = function () {
  101506. };
  101507. /** @hidden */
  101508. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  101509. if (faceIndex === void 0) { faceIndex = 0; }
  101510. if (lod === void 0) { lod = 0; }
  101511. };
  101512. /** @hidden */
  101513. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  101514. if (faceIndex === void 0) { faceIndex = 0; }
  101515. if (lod === void 0) { lod = 0; }
  101516. };
  101517. /** @hidden */
  101518. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  101519. if (faceIndex === void 0) { faceIndex = 0; }
  101520. if (lod === void 0) { lod = 0; }
  101521. };
  101522. /** @hidden */
  101523. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  101524. if (faceIndex === void 0) { faceIndex = 0; }
  101525. if (lod === void 0) { lod = 0; }
  101526. };
  101527. return NullEngine;
  101528. }(BABYLON.Engine));
  101529. BABYLON.NullEngine = NullEngine;
  101530. })(BABYLON || (BABYLON = {}));
  101531. //# sourceMappingURL=babylon.nullEngine.js.map
  101532. var BABYLON;
  101533. (function (BABYLON) {
  101534. /**
  101535. * This class can be used to get instrumentation data from a Babylon engine
  101536. */
  101537. var EngineInstrumentation = /** @class */ (function () {
  101538. function EngineInstrumentation(engine) {
  101539. this.engine = engine;
  101540. this._captureGPUFrameTime = false;
  101541. this._gpuFrameTime = new BABYLON.PerfCounter();
  101542. this._captureShaderCompilationTime = false;
  101543. this._shaderCompilationTime = new BABYLON.PerfCounter();
  101544. // Observers
  101545. this._onBeginFrameObserver = null;
  101546. this._onEndFrameObserver = null;
  101547. this._onBeforeShaderCompilationObserver = null;
  101548. this._onAfterShaderCompilationObserver = null;
  101549. }
  101550. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  101551. // Properties
  101552. /**
  101553. * Gets the perf counter used for GPU frame time
  101554. */
  101555. get: function () {
  101556. return this._gpuFrameTime;
  101557. },
  101558. enumerable: true,
  101559. configurable: true
  101560. });
  101561. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  101562. /**
  101563. * Gets the GPU frame time capture status
  101564. */
  101565. get: function () {
  101566. return this._captureGPUFrameTime;
  101567. },
  101568. /**
  101569. * Enable or disable the GPU frame time capture
  101570. */
  101571. set: function (value) {
  101572. var _this = this;
  101573. if (value === this._captureGPUFrameTime) {
  101574. return;
  101575. }
  101576. this._captureGPUFrameTime = value;
  101577. if (value) {
  101578. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  101579. if (!_this._gpuFrameTimeToken) {
  101580. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  101581. }
  101582. });
  101583. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  101584. if (!_this._gpuFrameTimeToken) {
  101585. return;
  101586. }
  101587. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  101588. if (time > -1) {
  101589. _this._gpuFrameTimeToken = null;
  101590. _this._gpuFrameTime.fetchNewFrame();
  101591. _this._gpuFrameTime.addCount(time, true);
  101592. }
  101593. });
  101594. }
  101595. else {
  101596. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101597. this._onBeginFrameObserver = null;
  101598. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101599. this._onEndFrameObserver = null;
  101600. }
  101601. },
  101602. enumerable: true,
  101603. configurable: true
  101604. });
  101605. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  101606. /**
  101607. * Gets the perf counter used for shader compilation time
  101608. */
  101609. get: function () {
  101610. return this._shaderCompilationTime;
  101611. },
  101612. enumerable: true,
  101613. configurable: true
  101614. });
  101615. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  101616. /**
  101617. * Gets the shader compilation time capture status
  101618. */
  101619. get: function () {
  101620. return this._captureShaderCompilationTime;
  101621. },
  101622. /**
  101623. * Enable or disable the shader compilation time capture
  101624. */
  101625. set: function (value) {
  101626. var _this = this;
  101627. if (value === this._captureShaderCompilationTime) {
  101628. return;
  101629. }
  101630. this._captureShaderCompilationTime = value;
  101631. if (value) {
  101632. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  101633. _this._shaderCompilationTime.fetchNewFrame();
  101634. _this._shaderCompilationTime.beginMonitoring();
  101635. });
  101636. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  101637. _this._shaderCompilationTime.endMonitoring();
  101638. });
  101639. }
  101640. else {
  101641. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101642. this._onBeforeShaderCompilationObserver = null;
  101643. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101644. this._onAfterShaderCompilationObserver = null;
  101645. }
  101646. },
  101647. enumerable: true,
  101648. configurable: true
  101649. });
  101650. EngineInstrumentation.prototype.dispose = function () {
  101651. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101652. this._onBeginFrameObserver = null;
  101653. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101654. this._onEndFrameObserver = null;
  101655. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101656. this._onBeforeShaderCompilationObserver = null;
  101657. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101658. this._onAfterShaderCompilationObserver = null;
  101659. this.engine = null;
  101660. };
  101661. return EngineInstrumentation;
  101662. }());
  101663. BABYLON.EngineInstrumentation = EngineInstrumentation;
  101664. })(BABYLON || (BABYLON = {}));
  101665. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  101666. var BABYLON;
  101667. (function (BABYLON) {
  101668. /**
  101669. * This class can be used to get instrumentation data from a Babylon engine
  101670. */
  101671. var SceneInstrumentation = /** @class */ (function () {
  101672. function SceneInstrumentation(scene) {
  101673. var _this = this;
  101674. this.scene = scene;
  101675. this._captureActiveMeshesEvaluationTime = false;
  101676. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  101677. this._captureRenderTargetsRenderTime = false;
  101678. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  101679. this._captureFrameTime = false;
  101680. this._frameTime = new BABYLON.PerfCounter();
  101681. this._captureRenderTime = false;
  101682. this._renderTime = new BABYLON.PerfCounter();
  101683. this._captureInterFrameTime = false;
  101684. this._interFrameTime = new BABYLON.PerfCounter();
  101685. this._captureParticlesRenderTime = false;
  101686. this._particlesRenderTime = new BABYLON.PerfCounter();
  101687. this._captureSpritesRenderTime = false;
  101688. this._spritesRenderTime = new BABYLON.PerfCounter();
  101689. this._capturePhysicsTime = false;
  101690. this._physicsTime = new BABYLON.PerfCounter();
  101691. this._captureAnimationsTime = false;
  101692. this._animationsTime = new BABYLON.PerfCounter();
  101693. this._captureCameraRenderTime = false;
  101694. this._cameraRenderTime = new BABYLON.PerfCounter();
  101695. // Observers
  101696. this._onBeforeActiveMeshesEvaluationObserver = null;
  101697. this._onAfterActiveMeshesEvaluationObserver = null;
  101698. this._onBeforeRenderTargetsRenderObserver = null;
  101699. this._onAfterRenderTargetsRenderObserver = null;
  101700. this._onAfterRenderObserver = null;
  101701. this._onBeforeDrawPhaseObserver = null;
  101702. this._onAfterDrawPhaseObserver = null;
  101703. this._onBeforeAnimationsObserver = null;
  101704. this._onBeforeParticlesRenderingObserver = null;
  101705. this._onAfterParticlesRenderingObserver = null;
  101706. this._onBeforeSpritesRenderingObserver = null;
  101707. this._onAfterSpritesRenderingObserver = null;
  101708. this._onBeforePhysicsObserver = null;
  101709. this._onAfterPhysicsObserver = null;
  101710. this._onAfterAnimationsObserver = null;
  101711. this._onBeforeCameraRenderObserver = null;
  101712. this._onAfterCameraRenderObserver = null;
  101713. // Before render
  101714. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  101715. if (_this._captureActiveMeshesEvaluationTime) {
  101716. _this._activeMeshesEvaluationTime.fetchNewFrame();
  101717. }
  101718. if (_this._captureRenderTargetsRenderTime) {
  101719. _this._renderTargetsRenderTime.fetchNewFrame();
  101720. }
  101721. if (_this._captureFrameTime) {
  101722. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  101723. _this._frameTime.beginMonitoring();
  101724. }
  101725. if (_this._captureInterFrameTime) {
  101726. _this._interFrameTime.endMonitoring();
  101727. }
  101728. if (_this._captureParticlesRenderTime) {
  101729. _this._particlesRenderTime.fetchNewFrame();
  101730. }
  101731. if (_this._captureSpritesRenderTime) {
  101732. _this._spritesRenderTime.fetchNewFrame();
  101733. }
  101734. if (_this._captureAnimationsTime) {
  101735. _this._animationsTime.beginMonitoring();
  101736. }
  101737. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  101738. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  101739. });
  101740. // After render
  101741. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  101742. if (_this._captureFrameTime) {
  101743. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  101744. _this._frameTime.endMonitoring();
  101745. }
  101746. if (_this._captureRenderTime) {
  101747. _this._renderTime.endMonitoring(false);
  101748. }
  101749. if (_this._captureInterFrameTime) {
  101750. _this._interFrameTime.beginMonitoring();
  101751. }
  101752. });
  101753. }
  101754. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  101755. // Properties
  101756. /**
  101757. * Gets the perf counter used for active meshes evaluation time
  101758. */
  101759. get: function () {
  101760. return this._activeMeshesEvaluationTime;
  101761. },
  101762. enumerable: true,
  101763. configurable: true
  101764. });
  101765. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  101766. /**
  101767. * Gets the active meshes evaluation time capture status
  101768. */
  101769. get: function () {
  101770. return this._captureActiveMeshesEvaluationTime;
  101771. },
  101772. /**
  101773. * Enable or disable the active meshes evaluation time capture
  101774. */
  101775. set: function (value) {
  101776. var _this = this;
  101777. if (value === this._captureActiveMeshesEvaluationTime) {
  101778. return;
  101779. }
  101780. this._captureActiveMeshesEvaluationTime = value;
  101781. if (value) {
  101782. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  101783. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  101784. _this._activeMeshesEvaluationTime.beginMonitoring();
  101785. });
  101786. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  101787. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  101788. _this._activeMeshesEvaluationTime.endMonitoring();
  101789. });
  101790. }
  101791. else {
  101792. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101793. this._onBeforeActiveMeshesEvaluationObserver = null;
  101794. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101795. this._onAfterActiveMeshesEvaluationObserver = null;
  101796. }
  101797. },
  101798. enumerable: true,
  101799. configurable: true
  101800. });
  101801. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  101802. /**
  101803. * Gets the perf counter used for render targets render time
  101804. */
  101805. get: function () {
  101806. return this._renderTargetsRenderTime;
  101807. },
  101808. enumerable: true,
  101809. configurable: true
  101810. });
  101811. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  101812. /**
  101813. * Gets the render targets render time capture status
  101814. */
  101815. get: function () {
  101816. return this._captureRenderTargetsRenderTime;
  101817. },
  101818. /**
  101819. * Enable or disable the render targets render time capture
  101820. */
  101821. set: function (value) {
  101822. var _this = this;
  101823. if (value === this._captureRenderTargetsRenderTime) {
  101824. return;
  101825. }
  101826. this._captureRenderTargetsRenderTime = value;
  101827. if (value) {
  101828. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  101829. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  101830. _this._renderTargetsRenderTime.beginMonitoring();
  101831. });
  101832. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  101833. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  101834. _this._renderTargetsRenderTime.endMonitoring(false);
  101835. });
  101836. }
  101837. else {
  101838. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101839. this._onBeforeRenderTargetsRenderObserver = null;
  101840. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101841. this._onAfterRenderTargetsRenderObserver = null;
  101842. }
  101843. },
  101844. enumerable: true,
  101845. configurable: true
  101846. });
  101847. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  101848. /**
  101849. * Gets the perf counter used for particles render time
  101850. */
  101851. get: function () {
  101852. return this._particlesRenderTime;
  101853. },
  101854. enumerable: true,
  101855. configurable: true
  101856. });
  101857. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  101858. /**
  101859. * Gets the particles render time capture status
  101860. */
  101861. get: function () {
  101862. return this._captureParticlesRenderTime;
  101863. },
  101864. /**
  101865. * Enable or disable the particles render time capture
  101866. */
  101867. set: function (value) {
  101868. var _this = this;
  101869. if (value === this._captureParticlesRenderTime) {
  101870. return;
  101871. }
  101872. this._captureParticlesRenderTime = value;
  101873. if (value) {
  101874. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101875. BABYLON.Tools.StartPerformanceCounter("Particles");
  101876. _this._particlesRenderTime.beginMonitoring();
  101877. });
  101878. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101879. BABYLON.Tools.EndPerformanceCounter("Particles");
  101880. _this._particlesRenderTime.endMonitoring(false);
  101881. });
  101882. }
  101883. else {
  101884. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101885. this._onBeforeParticlesRenderingObserver = null;
  101886. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101887. this._onAfterParticlesRenderingObserver = null;
  101888. }
  101889. },
  101890. enumerable: true,
  101891. configurable: true
  101892. });
  101893. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101894. /**
  101895. * Gets the perf counter used for sprites render time
  101896. */
  101897. get: function () {
  101898. return this._spritesRenderTime;
  101899. },
  101900. enumerable: true,
  101901. configurable: true
  101902. });
  101903. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101904. /**
  101905. * Gets the sprites render time capture status
  101906. */
  101907. get: function () {
  101908. return this._captureSpritesRenderTime;
  101909. },
  101910. /**
  101911. * Enable or disable the sprites render time capture
  101912. */
  101913. set: function (value) {
  101914. var _this = this;
  101915. if (value === this._captureSpritesRenderTime) {
  101916. return;
  101917. }
  101918. this._captureSpritesRenderTime = value;
  101919. if (value) {
  101920. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101921. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101922. _this._spritesRenderTime.beginMonitoring();
  101923. });
  101924. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101925. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101926. _this._spritesRenderTime.endMonitoring(false);
  101927. });
  101928. }
  101929. else {
  101930. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101931. this._onBeforeSpritesRenderingObserver = null;
  101932. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101933. this._onAfterSpritesRenderingObserver = null;
  101934. }
  101935. },
  101936. enumerable: true,
  101937. configurable: true
  101938. });
  101939. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101940. /**
  101941. * Gets the perf counter used for physics time
  101942. */
  101943. get: function () {
  101944. return this._physicsTime;
  101945. },
  101946. enumerable: true,
  101947. configurable: true
  101948. });
  101949. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101950. /**
  101951. * Gets the physics time capture status
  101952. */
  101953. get: function () {
  101954. return this._capturePhysicsTime;
  101955. },
  101956. /**
  101957. * Enable or disable the physics time capture
  101958. */
  101959. set: function (value) {
  101960. var _this = this;
  101961. if (value === this._capturePhysicsTime) {
  101962. return;
  101963. }
  101964. this._capturePhysicsTime = value;
  101965. if (value) {
  101966. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101967. BABYLON.Tools.StartPerformanceCounter("Physics");
  101968. _this._physicsTime.beginMonitoring();
  101969. });
  101970. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101971. BABYLON.Tools.EndPerformanceCounter("Physics");
  101972. _this._physicsTime.endMonitoring();
  101973. });
  101974. }
  101975. else {
  101976. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101977. this._onBeforePhysicsObserver = null;
  101978. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101979. this._onAfterPhysicsObserver = null;
  101980. }
  101981. },
  101982. enumerable: true,
  101983. configurable: true
  101984. });
  101985. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101986. /**
  101987. * Gets the perf counter used for animations time
  101988. */
  101989. get: function () {
  101990. return this._animationsTime;
  101991. },
  101992. enumerable: true,
  101993. configurable: true
  101994. });
  101995. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101996. /**
  101997. * Gets the animations time capture status
  101998. */
  101999. get: function () {
  102000. return this._captureAnimationsTime;
  102001. },
  102002. /**
  102003. * Enable or disable the animations time capture
  102004. */
  102005. set: function (value) {
  102006. var _this = this;
  102007. if (value === this._captureAnimationsTime) {
  102008. return;
  102009. }
  102010. this._captureAnimationsTime = value;
  102011. if (value) {
  102012. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  102013. _this._animationsTime.endMonitoring();
  102014. });
  102015. }
  102016. else {
  102017. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102018. this._onAfterAnimationsObserver = null;
  102019. }
  102020. },
  102021. enumerable: true,
  102022. configurable: true
  102023. });
  102024. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  102025. /**
  102026. * Gets the perf counter used for frame time capture
  102027. */
  102028. get: function () {
  102029. return this._frameTime;
  102030. },
  102031. enumerable: true,
  102032. configurable: true
  102033. });
  102034. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  102035. /**
  102036. * Gets the frame time capture status
  102037. */
  102038. get: function () {
  102039. return this._captureFrameTime;
  102040. },
  102041. /**
  102042. * Enable or disable the frame time capture
  102043. */
  102044. set: function (value) {
  102045. this._captureFrameTime = value;
  102046. },
  102047. enumerable: true,
  102048. configurable: true
  102049. });
  102050. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  102051. /**
  102052. * Gets the perf counter used for inter-frames time capture
  102053. */
  102054. get: function () {
  102055. return this._interFrameTime;
  102056. },
  102057. enumerable: true,
  102058. configurable: true
  102059. });
  102060. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  102061. /**
  102062. * Gets the inter-frames time capture status
  102063. */
  102064. get: function () {
  102065. return this._captureInterFrameTime;
  102066. },
  102067. /**
  102068. * Enable or disable the inter-frames time capture
  102069. */
  102070. set: function (value) {
  102071. this._captureInterFrameTime = value;
  102072. },
  102073. enumerable: true,
  102074. configurable: true
  102075. });
  102076. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  102077. /**
  102078. * Gets the perf counter used for render time capture
  102079. */
  102080. get: function () {
  102081. return this._renderTime;
  102082. },
  102083. enumerable: true,
  102084. configurable: true
  102085. });
  102086. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  102087. /**
  102088. * Gets the render time capture status
  102089. */
  102090. get: function () {
  102091. return this._captureRenderTime;
  102092. },
  102093. /**
  102094. * Enable or disable the render time capture
  102095. */
  102096. set: function (value) {
  102097. var _this = this;
  102098. if (value === this._captureRenderTime) {
  102099. return;
  102100. }
  102101. this._captureRenderTime = value;
  102102. if (value) {
  102103. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  102104. _this._renderTime.beginMonitoring();
  102105. BABYLON.Tools.StartPerformanceCounter("Main render");
  102106. });
  102107. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  102108. _this._renderTime.endMonitoring(false);
  102109. BABYLON.Tools.EndPerformanceCounter("Main render");
  102110. });
  102111. }
  102112. else {
  102113. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102114. this._onBeforeDrawPhaseObserver = null;
  102115. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102116. this._onAfterDrawPhaseObserver = null;
  102117. }
  102118. },
  102119. enumerable: true,
  102120. configurable: true
  102121. });
  102122. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  102123. /**
  102124. * Gets the perf counter used for camera render time capture
  102125. */
  102126. get: function () {
  102127. return this._cameraRenderTime;
  102128. },
  102129. enumerable: true,
  102130. configurable: true
  102131. });
  102132. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  102133. /**
  102134. * Gets the camera render time capture status
  102135. */
  102136. get: function () {
  102137. return this._captureCameraRenderTime;
  102138. },
  102139. /**
  102140. * Enable or disable the camera render time capture
  102141. */
  102142. set: function (value) {
  102143. var _this = this;
  102144. if (value === this._captureCameraRenderTime) {
  102145. return;
  102146. }
  102147. this._captureCameraRenderTime = value;
  102148. if (value) {
  102149. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  102150. _this._cameraRenderTime.beginMonitoring();
  102151. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  102152. });
  102153. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  102154. _this._cameraRenderTime.endMonitoring(false);
  102155. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  102156. });
  102157. }
  102158. else {
  102159. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102160. this._onBeforeCameraRenderObserver = null;
  102161. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102162. this._onAfterCameraRenderObserver = null;
  102163. }
  102164. },
  102165. enumerable: true,
  102166. configurable: true
  102167. });
  102168. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  102169. /**
  102170. * Gets the perf counter used for draw calls
  102171. */
  102172. get: function () {
  102173. return this.scene.getEngine()._drawCalls;
  102174. },
  102175. enumerable: true,
  102176. configurable: true
  102177. });
  102178. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  102179. /**
  102180. * Gets the perf counter used for texture collisions
  102181. */
  102182. get: function () {
  102183. return this.scene.getEngine()._textureCollisions;
  102184. },
  102185. enumerable: true,
  102186. configurable: true
  102187. });
  102188. SceneInstrumentation.prototype.dispose = function () {
  102189. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102190. this._onAfterRenderObserver = null;
  102191. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102192. this._onBeforeActiveMeshesEvaluationObserver = null;
  102193. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102194. this._onAfterActiveMeshesEvaluationObserver = null;
  102195. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102196. this._onBeforeRenderTargetsRenderObserver = null;
  102197. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102198. this._onAfterRenderTargetsRenderObserver = null;
  102199. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  102200. this._onBeforeAnimationsObserver = null;
  102201. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102202. this._onBeforeParticlesRenderingObserver = null;
  102203. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102204. this._onAfterParticlesRenderingObserver = null;
  102205. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102206. this._onBeforeSpritesRenderingObserver = null;
  102207. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102208. this._onAfterSpritesRenderingObserver = null;
  102209. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102210. this._onBeforeDrawPhaseObserver = null;
  102211. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102212. this._onAfterDrawPhaseObserver = null;
  102213. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102214. this._onBeforePhysicsObserver = null;
  102215. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102216. this._onAfterPhysicsObserver = null;
  102217. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102218. this._onAfterAnimationsObserver = null;
  102219. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102220. this._onBeforeCameraRenderObserver = null;
  102221. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102222. this._onAfterCameraRenderObserver = null;
  102223. this.scene = null;
  102224. };
  102225. return SceneInstrumentation;
  102226. }());
  102227. BABYLON.SceneInstrumentation = SceneInstrumentation;
  102228. })(BABYLON || (BABYLON = {}));
  102229. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  102230. var BABYLON;
  102231. (function (BABYLON) {
  102232. /**
  102233. * @hidden
  102234. **/
  102235. var _TimeToken = /** @class */ (function () {
  102236. function _TimeToken() {
  102237. this._timeElapsedQueryEnded = false;
  102238. }
  102239. return _TimeToken;
  102240. }());
  102241. BABYLON._TimeToken = _TimeToken;
  102242. })(BABYLON || (BABYLON = {}));
  102243. //# sourceMappingURL=babylon.timeToken.js.map
  102244. var BABYLON;
  102245. (function (BABYLON) {
  102246. /**
  102247. * Background material defines definition.
  102248. * @hidden Mainly internal Use
  102249. */
  102250. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  102251. __extends(BackgroundMaterialDefines, _super);
  102252. /**
  102253. * Constructor of the defines.
  102254. */
  102255. function BackgroundMaterialDefines() {
  102256. var _this = _super.call(this) || this;
  102257. /**
  102258. * True if the diffuse texture is in use.
  102259. */
  102260. _this.DIFFUSE = false;
  102261. /**
  102262. * The direct UV channel to use.
  102263. */
  102264. _this.DIFFUSEDIRECTUV = 0;
  102265. /**
  102266. * True if the diffuse texture is in gamma space.
  102267. */
  102268. _this.GAMMADIFFUSE = false;
  102269. /**
  102270. * True if the diffuse texture has opacity in the alpha channel.
  102271. */
  102272. _this.DIFFUSEHASALPHA = false;
  102273. /**
  102274. * True if you want the material to fade to transparent at grazing angle.
  102275. */
  102276. _this.OPACITYFRESNEL = false;
  102277. /**
  102278. * True if an extra blur needs to be added in the reflection.
  102279. */
  102280. _this.REFLECTIONBLUR = false;
  102281. /**
  102282. * True if you want the material to fade to reflection at grazing angle.
  102283. */
  102284. _this.REFLECTIONFRESNEL = false;
  102285. /**
  102286. * True if you want the material to falloff as far as you move away from the scene center.
  102287. */
  102288. _this.REFLECTIONFALLOFF = false;
  102289. /**
  102290. * False if the current Webgl implementation does not support the texture lod extension.
  102291. */
  102292. _this.TEXTURELODSUPPORT = false;
  102293. /**
  102294. * True to ensure the data are premultiplied.
  102295. */
  102296. _this.PREMULTIPLYALPHA = false;
  102297. /**
  102298. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  102299. */
  102300. _this.USERGBCOLOR = false;
  102301. /**
  102302. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  102303. * stays aligned with the desired configuration.
  102304. */
  102305. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  102306. /**
  102307. * True to add noise in order to reduce the banding effect.
  102308. */
  102309. _this.NOISE = false;
  102310. /**
  102311. * is the reflection texture in BGR color scheme?
  102312. * Mainly used to solve a bug in ios10 video tag
  102313. */
  102314. _this.REFLECTIONBGR = false;
  102315. _this.IMAGEPROCESSING = false;
  102316. _this.VIGNETTE = false;
  102317. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  102318. _this.VIGNETTEBLENDMODEOPAQUE = false;
  102319. _this.TONEMAPPING = false;
  102320. _this.CONTRAST = false;
  102321. _this.COLORCURVES = false;
  102322. _this.COLORGRADING = false;
  102323. _this.COLORGRADING3D = false;
  102324. _this.SAMPLER3DGREENDEPTH = false;
  102325. _this.SAMPLER3DBGRMAP = false;
  102326. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  102327. _this.EXPOSURE = false;
  102328. // Reflection.
  102329. _this.REFLECTION = false;
  102330. _this.REFLECTIONMAP_3D = false;
  102331. _this.REFLECTIONMAP_SPHERICAL = false;
  102332. _this.REFLECTIONMAP_PLANAR = false;
  102333. _this.REFLECTIONMAP_CUBIC = false;
  102334. _this.REFLECTIONMAP_PROJECTION = false;
  102335. _this.REFLECTIONMAP_SKYBOX = false;
  102336. _this.REFLECTIONMAP_EXPLICIT = false;
  102337. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102338. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102339. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102340. _this.INVERTCUBICMAP = false;
  102341. _this.REFLECTIONMAP_OPPOSITEZ = false;
  102342. _this.LODINREFLECTIONALPHA = false;
  102343. _this.GAMMAREFLECTION = false;
  102344. _this.RGBDREFLECTION = false;
  102345. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  102346. // Default BJS.
  102347. _this.MAINUV1 = false;
  102348. _this.MAINUV2 = false;
  102349. _this.UV1 = false;
  102350. _this.UV2 = false;
  102351. _this.CLIPPLANE = false;
  102352. _this.POINTSIZE = false;
  102353. _this.FOG = false;
  102354. _this.NORMAL = false;
  102355. _this.NUM_BONE_INFLUENCERS = 0;
  102356. _this.BonesPerMesh = 0;
  102357. _this.INSTANCES = false;
  102358. _this.SHADOWFLOAT = false;
  102359. _this.rebuild();
  102360. return _this;
  102361. }
  102362. return BackgroundMaterialDefines;
  102363. }(BABYLON.MaterialDefines));
  102364. /**
  102365. * Background material used to create an efficient environement around your scene.
  102366. */
  102367. var BackgroundMaterial = /** @class */ (function (_super) {
  102368. __extends(BackgroundMaterial, _super);
  102369. /**
  102370. * Instantiates a Background Material in the given scene
  102371. * @param name The friendly name of the material
  102372. * @param scene The scene to add the material to
  102373. */
  102374. function BackgroundMaterial(name, scene) {
  102375. var _this = _super.call(this, name, scene) || this;
  102376. /**
  102377. * Key light Color (multiply against the environement texture)
  102378. */
  102379. _this.primaryColor = BABYLON.Color3.White();
  102380. _this._primaryColorShadowLevel = 0;
  102381. _this._primaryColorHighlightLevel = 0;
  102382. /**
  102383. * Reflection Texture used in the material.
  102384. * Should be author in a specific way for the best result (refer to the documentation).
  102385. */
  102386. _this.reflectionTexture = null;
  102387. /**
  102388. * Reflection Texture level of blur.
  102389. *
  102390. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  102391. * texture twice.
  102392. */
  102393. _this.reflectionBlur = 0;
  102394. /**
  102395. * Diffuse Texture used in the material.
  102396. * Should be author in a specific way for the best result (refer to the documentation).
  102397. */
  102398. _this.diffuseTexture = null;
  102399. _this._shadowLights = null;
  102400. /**
  102401. * Specify the list of lights casting shadow on the material.
  102402. * All scene shadow lights will be included if null.
  102403. */
  102404. _this.shadowLights = null;
  102405. /**
  102406. * Helps adjusting the shadow to a softer level if required.
  102407. * 0 means black shadows and 1 means no shadows.
  102408. */
  102409. _this.shadowLevel = 0;
  102410. /**
  102411. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  102412. * It is usually zero but might be interesting to modify according to your setup.
  102413. */
  102414. _this.sceneCenter = BABYLON.Vector3.Zero();
  102415. /**
  102416. * This helps specifying that the material is falling off to the sky box at grazing angle.
  102417. * This helps ensuring a nice transition when the camera goes under the ground.
  102418. */
  102419. _this.opacityFresnel = true;
  102420. /**
  102421. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  102422. * This helps adding a mirror texture on the ground.
  102423. */
  102424. _this.reflectionFresnel = false;
  102425. /**
  102426. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  102427. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  102428. */
  102429. _this.reflectionFalloffDistance = 0.0;
  102430. /**
  102431. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  102432. */
  102433. _this.reflectionAmount = 1.0;
  102434. /**
  102435. * This specifies the weight of the reflection at grazing angle.
  102436. */
  102437. _this.reflectionReflectance0 = 0.05;
  102438. /**
  102439. * This specifies the weight of the reflection at a perpendicular point of view.
  102440. */
  102441. _this.reflectionReflectance90 = 0.5;
  102442. /**
  102443. * Helps to directly use the maps channels instead of their level.
  102444. */
  102445. _this.useRGBColor = true;
  102446. /**
  102447. * This helps reducing the banding effect that could occur on the background.
  102448. */
  102449. _this.enableNoise = false;
  102450. _this._fovMultiplier = 1.0;
  102451. /**
  102452. * Enable the FOV adjustment feature controlled by fovMultiplier.
  102453. */
  102454. _this.useEquirectangularFOV = false;
  102455. _this._maxSimultaneousLights = 4;
  102456. /**
  102457. * Number of Simultaneous lights allowed on the material.
  102458. */
  102459. _this.maxSimultaneousLights = 4;
  102460. /**
  102461. * Keep track of the image processing observer to allow dispose and replace.
  102462. */
  102463. _this._imageProcessingObserver = null;
  102464. /**
  102465. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  102466. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  102467. */
  102468. _this.switchToBGR = false;
  102469. // Temp values kept as cache in the material.
  102470. _this._renderTargets = new BABYLON.SmartArray(16);
  102471. _this._reflectionControls = BABYLON.Vector4.Zero();
  102472. _this._white = BABYLON.Color3.White();
  102473. _this._primaryShadowColor = BABYLON.Color3.Black();
  102474. _this._primaryHighlightColor = BABYLON.Color3.Black();
  102475. // Setup the default processing configuration to the scene.
  102476. _this._attachImageProcessingConfiguration(null);
  102477. _this.getRenderTargetTextures = function () {
  102478. _this._renderTargets.reset();
  102479. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  102480. _this._renderTargets.push(_this._diffuseTexture);
  102481. }
  102482. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  102483. _this._renderTargets.push(_this._reflectionTexture);
  102484. }
  102485. return _this._renderTargets;
  102486. };
  102487. return _this;
  102488. }
  102489. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  102490. /**
  102491. * Experimental Internal Use Only.
  102492. *
  102493. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  102494. * This acts as a helper to set the primary color to a more "human friendly" value.
  102495. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  102496. * output color as close as possible from the chosen value.
  102497. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  102498. * part of lighting setup.)
  102499. */
  102500. get: function () {
  102501. return this.__perceptualColor;
  102502. },
  102503. set: function (value) {
  102504. this.__perceptualColor = value;
  102505. this._computePrimaryColorFromPerceptualColor();
  102506. this._markAllSubMeshesAsLightsDirty();
  102507. },
  102508. enumerable: true,
  102509. configurable: true
  102510. });
  102511. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  102512. /**
  102513. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  102514. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  102515. */
  102516. get: function () {
  102517. return this._primaryColorShadowLevel;
  102518. },
  102519. set: function (value) {
  102520. this._primaryColorShadowLevel = value;
  102521. this._computePrimaryColors();
  102522. this._markAllSubMeshesAsLightsDirty();
  102523. },
  102524. enumerable: true,
  102525. configurable: true
  102526. });
  102527. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  102528. /**
  102529. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  102530. * The primary color is used at the level chosen to define what the white area would look.
  102531. */
  102532. get: function () {
  102533. return this._primaryColorHighlightLevel;
  102534. },
  102535. set: function (value) {
  102536. this._primaryColorHighlightLevel = value;
  102537. this._computePrimaryColors();
  102538. this._markAllSubMeshesAsLightsDirty();
  102539. },
  102540. enumerable: true,
  102541. configurable: true
  102542. });
  102543. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  102544. /**
  102545. * Sets the reflection reflectance fresnel values according to the default standard
  102546. * empirically know to work well :-)
  102547. */
  102548. set: function (value) {
  102549. var reflectionWeight = value;
  102550. if (reflectionWeight < 0.5) {
  102551. reflectionWeight = reflectionWeight * 2.0;
  102552. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  102553. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  102554. }
  102555. else {
  102556. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  102557. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  102558. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  102559. }
  102560. },
  102561. enumerable: true,
  102562. configurable: true
  102563. });
  102564. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  102565. /**
  102566. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102567. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  102568. * Recommended to be keep at 1.0 except for special cases.
  102569. */
  102570. get: function () {
  102571. return this._fovMultiplier;
  102572. },
  102573. set: function (value) {
  102574. if (isNaN(value)) {
  102575. value = 1.0;
  102576. }
  102577. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  102578. },
  102579. enumerable: true,
  102580. configurable: true
  102581. });
  102582. /**
  102583. * Attaches a new image processing configuration to the PBR Material.
  102584. * @param configuration (if null the scene configuration will be use)
  102585. */
  102586. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  102587. var _this = this;
  102588. if (configuration === this._imageProcessingConfiguration) {
  102589. return;
  102590. }
  102591. // Detaches observer.
  102592. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102593. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102594. }
  102595. // Pick the scene configuration if needed.
  102596. if (!configuration) {
  102597. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  102598. }
  102599. else {
  102600. this._imageProcessingConfiguration = configuration;
  102601. }
  102602. // Attaches observer.
  102603. if (this._imageProcessingConfiguration) {
  102604. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  102605. _this._computePrimaryColorFromPerceptualColor();
  102606. _this._markAllSubMeshesAsImageProcessingDirty();
  102607. });
  102608. }
  102609. };
  102610. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  102611. /**
  102612. * Gets the image processing configuration used either in this material.
  102613. */
  102614. get: function () {
  102615. return this._imageProcessingConfiguration;
  102616. },
  102617. /**
  102618. * Sets the Default image processing configuration used either in the this material.
  102619. *
  102620. * If sets to null, the scene one is in use.
  102621. */
  102622. set: function (value) {
  102623. this._attachImageProcessingConfiguration(value);
  102624. // Ensure the effect will be rebuilt.
  102625. this._markAllSubMeshesAsTexturesDirty();
  102626. },
  102627. enumerable: true,
  102628. configurable: true
  102629. });
  102630. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  102631. /**
  102632. * Gets wether the color curves effect is enabled.
  102633. */
  102634. get: function () {
  102635. return this.imageProcessingConfiguration.colorCurvesEnabled;
  102636. },
  102637. /**
  102638. * Sets wether the color curves effect is enabled.
  102639. */
  102640. set: function (value) {
  102641. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  102642. },
  102643. enumerable: true,
  102644. configurable: true
  102645. });
  102646. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  102647. /**
  102648. * Gets wether the color grading effect is enabled.
  102649. */
  102650. get: function () {
  102651. return this.imageProcessingConfiguration.colorGradingEnabled;
  102652. },
  102653. /**
  102654. * Gets wether the color grading effect is enabled.
  102655. */
  102656. set: function (value) {
  102657. this.imageProcessingConfiguration.colorGradingEnabled = value;
  102658. },
  102659. enumerable: true,
  102660. configurable: true
  102661. });
  102662. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  102663. /**
  102664. * Gets wether tonemapping is enabled or not.
  102665. */
  102666. get: function () {
  102667. return this._imageProcessingConfiguration.toneMappingEnabled;
  102668. },
  102669. /**
  102670. * Sets wether tonemapping is enabled or not
  102671. */
  102672. set: function (value) {
  102673. this._imageProcessingConfiguration.toneMappingEnabled = value;
  102674. },
  102675. enumerable: true,
  102676. configurable: true
  102677. });
  102678. ;
  102679. ;
  102680. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  102681. /**
  102682. * The camera exposure used on this material.
  102683. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102684. * This corresponds to a photographic exposure.
  102685. */
  102686. get: function () {
  102687. return this._imageProcessingConfiguration.exposure;
  102688. },
  102689. /**
  102690. * The camera exposure used on this material.
  102691. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102692. * This corresponds to a photographic exposure.
  102693. */
  102694. set: function (value) {
  102695. this._imageProcessingConfiguration.exposure = value;
  102696. },
  102697. enumerable: true,
  102698. configurable: true
  102699. });
  102700. ;
  102701. ;
  102702. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  102703. /**
  102704. * Gets The camera contrast used on this material.
  102705. */
  102706. get: function () {
  102707. return this._imageProcessingConfiguration.contrast;
  102708. },
  102709. /**
  102710. * Sets The camera contrast used on this material.
  102711. */
  102712. set: function (value) {
  102713. this._imageProcessingConfiguration.contrast = value;
  102714. },
  102715. enumerable: true,
  102716. configurable: true
  102717. });
  102718. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  102719. /**
  102720. * Gets the Color Grading 2D Lookup Texture.
  102721. */
  102722. get: function () {
  102723. return this._imageProcessingConfiguration.colorGradingTexture;
  102724. },
  102725. /**
  102726. * Sets the Color Grading 2D Lookup Texture.
  102727. */
  102728. set: function (value) {
  102729. this.imageProcessingConfiguration.colorGradingTexture = value;
  102730. },
  102731. enumerable: true,
  102732. configurable: true
  102733. });
  102734. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  102735. /**
  102736. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102737. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102738. * 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;
  102739. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102740. */
  102741. get: function () {
  102742. return this.imageProcessingConfiguration.colorCurves;
  102743. },
  102744. /**
  102745. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102746. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102747. * 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;
  102748. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102749. */
  102750. set: function (value) {
  102751. this.imageProcessingConfiguration.colorCurves = value;
  102752. },
  102753. enumerable: true,
  102754. configurable: true
  102755. });
  102756. /**
  102757. * The entire material has been created in order to prevent overdraw.
  102758. * @returns false
  102759. */
  102760. BackgroundMaterial.prototype.needAlphaTesting = function () {
  102761. return true;
  102762. };
  102763. /**
  102764. * The entire material has been created in order to prevent overdraw.
  102765. * @returns true if blending is enable
  102766. */
  102767. BackgroundMaterial.prototype.needAlphaBlending = function () {
  102768. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  102769. };
  102770. /**
  102771. * Checks wether the material is ready to be rendered for a given mesh.
  102772. * @param mesh The mesh to render
  102773. * @param subMesh The submesh to check against
  102774. * @param useInstances Specify wether or not the material is used with instances
  102775. * @returns true if all the dependencies are ready (Textures, Effects...)
  102776. */
  102777. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  102778. var _this = this;
  102779. if (useInstances === void 0) { useInstances = false; }
  102780. if (subMesh.effect && this.isFrozen) {
  102781. if (this._wasPreviouslyReady) {
  102782. return true;
  102783. }
  102784. }
  102785. if (!subMesh._materialDefines) {
  102786. subMesh._materialDefines = new BackgroundMaterialDefines();
  102787. }
  102788. var scene = this.getScene();
  102789. var defines = subMesh._materialDefines;
  102790. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  102791. if (defines._renderId === scene.getRenderId()) {
  102792. return true;
  102793. }
  102794. }
  102795. var engine = scene.getEngine();
  102796. // Lights
  102797. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  102798. defines._needNormals = true;
  102799. // Textures
  102800. if (defines._areTexturesDirty) {
  102801. defines._needUVs = false;
  102802. if (scene.texturesEnabled) {
  102803. if (scene.getEngine().getCaps().textureLOD) {
  102804. defines.TEXTURELODSUPPORT = true;
  102805. }
  102806. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102807. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  102808. return false;
  102809. }
  102810. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  102811. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  102812. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  102813. defines.OPACITYFRESNEL = this._opacityFresnel;
  102814. }
  102815. else {
  102816. defines.DIFFUSE = false;
  102817. defines.DIFFUSEHASALPHA = false;
  102818. defines.GAMMADIFFUSE = false;
  102819. defines.OPACITYFRESNEL = false;
  102820. }
  102821. var reflectionTexture = this._reflectionTexture;
  102822. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102823. if (!reflectionTexture.isReadyOrNotBlocking()) {
  102824. return false;
  102825. }
  102826. defines.REFLECTION = true;
  102827. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  102828. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  102829. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  102830. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  102831. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  102832. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  102833. defines.REFLECTIONBGR = this.switchToBGR;
  102834. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  102835. defines.INVERTCUBICMAP = true;
  102836. }
  102837. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  102838. switch (reflectionTexture.coordinatesMode) {
  102839. case BABYLON.Texture.EXPLICIT_MODE:
  102840. defines.REFLECTIONMAP_EXPLICIT = true;
  102841. break;
  102842. case BABYLON.Texture.PLANAR_MODE:
  102843. defines.REFLECTIONMAP_PLANAR = true;
  102844. break;
  102845. case BABYLON.Texture.PROJECTION_MODE:
  102846. defines.REFLECTIONMAP_PROJECTION = true;
  102847. break;
  102848. case BABYLON.Texture.SKYBOX_MODE:
  102849. defines.REFLECTIONMAP_SKYBOX = true;
  102850. break;
  102851. case BABYLON.Texture.SPHERICAL_MODE:
  102852. defines.REFLECTIONMAP_SPHERICAL = true;
  102853. break;
  102854. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  102855. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  102856. break;
  102857. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  102858. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102859. break;
  102860. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102861. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102862. break;
  102863. case BABYLON.Texture.CUBIC_MODE:
  102864. case BABYLON.Texture.INVCUBIC_MODE:
  102865. default:
  102866. defines.REFLECTIONMAP_CUBIC = true;
  102867. break;
  102868. }
  102869. if (this.reflectionFresnel) {
  102870. defines.REFLECTIONFRESNEL = true;
  102871. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102872. this._reflectionControls.x = this.reflectionAmount;
  102873. this._reflectionControls.y = this.reflectionReflectance0;
  102874. this._reflectionControls.z = this.reflectionReflectance90;
  102875. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102876. }
  102877. else {
  102878. defines.REFLECTIONFRESNEL = false;
  102879. defines.REFLECTIONFALLOFF = false;
  102880. }
  102881. }
  102882. else {
  102883. defines.REFLECTION = false;
  102884. defines.REFLECTIONFRESNEL = false;
  102885. defines.REFLECTIONFALLOFF = false;
  102886. defines.REFLECTIONBLUR = false;
  102887. defines.REFLECTIONMAP_3D = false;
  102888. defines.REFLECTIONMAP_SPHERICAL = false;
  102889. defines.REFLECTIONMAP_PLANAR = false;
  102890. defines.REFLECTIONMAP_CUBIC = false;
  102891. defines.REFLECTIONMAP_PROJECTION = false;
  102892. defines.REFLECTIONMAP_SKYBOX = false;
  102893. defines.REFLECTIONMAP_EXPLICIT = false;
  102894. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102895. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102896. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102897. defines.INVERTCUBICMAP = false;
  102898. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102899. defines.LODINREFLECTIONALPHA = false;
  102900. defines.GAMMAREFLECTION = false;
  102901. defines.RGBDREFLECTION = false;
  102902. }
  102903. }
  102904. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102905. defines.USERGBCOLOR = this._useRGBColor;
  102906. defines.NOISE = this._enableNoise;
  102907. }
  102908. if (defines._areLightsDirty) {
  102909. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102910. }
  102911. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102912. if (!this._imageProcessingConfiguration.isReady()) {
  102913. return false;
  102914. }
  102915. this._imageProcessingConfiguration.prepareDefines(defines);
  102916. }
  102917. // Misc.
  102918. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102919. // Values that need to be evaluated on every frame
  102920. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102921. // Attribs
  102922. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102923. if (mesh) {
  102924. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102925. mesh.createNormals(true);
  102926. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102927. }
  102928. }
  102929. }
  102930. // Get correct effect
  102931. if (defines.isDirty) {
  102932. defines.markAsProcessed();
  102933. scene.resetCachedMaterial();
  102934. // Fallbacks
  102935. var fallbacks = new BABYLON.EffectFallbacks();
  102936. if (defines.FOG) {
  102937. fallbacks.addFallback(0, "FOG");
  102938. }
  102939. if (defines.POINTSIZE) {
  102940. fallbacks.addFallback(1, "POINTSIZE");
  102941. }
  102942. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102943. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102944. fallbacks.addCPUSkinningFallback(0, mesh);
  102945. }
  102946. //Attributes
  102947. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102948. if (defines.NORMAL) {
  102949. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102950. }
  102951. if (defines.UV1) {
  102952. attribs.push(BABYLON.VertexBuffer.UVKind);
  102953. }
  102954. if (defines.UV2) {
  102955. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102956. }
  102957. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102958. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102959. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102960. "vFogInfos", "vFogColor", "pointSize",
  102961. "vClipPlane", "mBones",
  102962. "vPrimaryColor", "vPrimaryColorShadow",
  102963. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102964. "shadowLevel", "alpha",
  102965. "vBackgroundCenter", "vReflectionControl",
  102966. "vDiffuseInfos", "diffuseMatrix",
  102967. ];
  102968. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102969. var uniformBuffers = ["Material", "Scene"];
  102970. if (BABYLON.ImageProcessingConfiguration) {
  102971. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102972. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102973. }
  102974. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102975. uniformsNames: uniforms,
  102976. uniformBuffersNames: uniformBuffers,
  102977. samplers: samplers,
  102978. defines: defines,
  102979. maxSimultaneousLights: this._maxSimultaneousLights
  102980. });
  102981. var onCompiled = function (effect) {
  102982. if (_this.onCompiled) {
  102983. _this.onCompiled(effect);
  102984. }
  102985. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102986. };
  102987. var join = defines.toString();
  102988. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102989. attributes: attribs,
  102990. uniformsNames: uniforms,
  102991. uniformBuffersNames: uniformBuffers,
  102992. samplers: samplers,
  102993. defines: join,
  102994. fallbacks: fallbacks,
  102995. onCompiled: onCompiled,
  102996. onError: this.onError,
  102997. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102998. }, engine), defines);
  102999. this.buildUniformLayout();
  103000. }
  103001. if (!subMesh.effect || !subMesh.effect.isReady()) {
  103002. return false;
  103003. }
  103004. defines._renderId = scene.getRenderId();
  103005. this._wasPreviouslyReady = true;
  103006. return true;
  103007. };
  103008. /**
  103009. * Compute the primary color according to the chosen perceptual color.
  103010. */
  103011. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  103012. if (!this.__perceptualColor) {
  103013. return;
  103014. }
  103015. this._primaryColor.copyFrom(this.__perceptualColor);
  103016. // Revert gamma space.
  103017. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  103018. // Revert image processing configuration.
  103019. if (this._imageProcessingConfiguration) {
  103020. // Revert Exposure.
  103021. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  103022. }
  103023. this._computePrimaryColors();
  103024. };
  103025. /**
  103026. * Compute the highlights and shadow colors according to their chosen levels.
  103027. */
  103028. BackgroundMaterial.prototype._computePrimaryColors = function () {
  103029. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  103030. return;
  103031. }
  103032. // Find the highlight color based on the configuration.
  103033. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  103034. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  103035. // Find the shadow color based on the configuration.
  103036. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  103037. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  103038. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  103039. };
  103040. /**
  103041. * Build the uniform buffer used in the material.
  103042. */
  103043. BackgroundMaterial.prototype.buildUniformLayout = function () {
  103044. // Order is important !
  103045. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  103046. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  103047. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  103048. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  103049. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  103050. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  103051. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  103052. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  103053. this._uniformBuffer.addUniform("pointSize", 1);
  103054. this._uniformBuffer.addUniform("shadowLevel", 1);
  103055. this._uniformBuffer.addUniform("alpha", 1);
  103056. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  103057. this._uniformBuffer.addUniform("vReflectionControl", 4);
  103058. this._uniformBuffer.create();
  103059. };
  103060. /**
  103061. * Unbind the material.
  103062. */
  103063. BackgroundMaterial.prototype.unbind = function () {
  103064. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  103065. this._uniformBuffer.setTexture("diffuseSampler", null);
  103066. }
  103067. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  103068. this._uniformBuffer.setTexture("reflectionSampler", null);
  103069. }
  103070. _super.prototype.unbind.call(this);
  103071. };
  103072. /**
  103073. * Bind only the world matrix to the material.
  103074. * @param world The world matrix to bind.
  103075. */
  103076. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  103077. this._activeEffect.setMatrix("world", world);
  103078. };
  103079. /**
  103080. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  103081. * @param world The world matrix to bind.
  103082. * @param subMesh The submesh to bind for.
  103083. */
  103084. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  103085. var scene = this.getScene();
  103086. var defines = subMesh._materialDefines;
  103087. if (!defines) {
  103088. return;
  103089. }
  103090. var effect = subMesh.effect;
  103091. if (!effect) {
  103092. return;
  103093. }
  103094. this._activeEffect = effect;
  103095. // Matrices
  103096. this.bindOnlyWorldMatrix(world);
  103097. // Bones
  103098. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  103099. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  103100. if (mustRebind) {
  103101. this._uniformBuffer.bindToEffect(effect, "Material");
  103102. this.bindViewProjection(effect);
  103103. var reflectionTexture = this._reflectionTexture;
  103104. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  103105. // Texture uniforms
  103106. if (scene.texturesEnabled) {
  103107. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103108. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  103109. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  103110. }
  103111. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103112. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  103113. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  103114. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  103115. }
  103116. }
  103117. if (this.shadowLevel > 0) {
  103118. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  103119. }
  103120. this._uniformBuffer.updateFloat("alpha", this.alpha);
  103121. // Point size
  103122. if (this.pointsCloud) {
  103123. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  103124. }
  103125. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  103126. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  103127. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  103128. }
  103129. else {
  103130. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  103131. }
  103132. }
  103133. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  103134. // Textures
  103135. if (scene.texturesEnabled) {
  103136. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103137. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  103138. }
  103139. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103140. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  103141. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103142. }
  103143. else if (!defines.REFLECTIONBLUR) {
  103144. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103145. }
  103146. else {
  103147. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  103148. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  103149. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  103150. }
  103151. if (defines.REFLECTIONFRESNEL) {
  103152. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  103153. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  103154. }
  103155. }
  103156. }
  103157. // Clip plane
  103158. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  103159. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  103160. }
  103161. if (mustRebind || !this.isFrozen) {
  103162. if (scene.lightsEnabled) {
  103163. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  103164. }
  103165. // View
  103166. this.bindView(effect);
  103167. // Fog
  103168. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  103169. // image processing
  103170. if (this._imageProcessingConfiguration) {
  103171. this._imageProcessingConfiguration.bind(this._activeEffect);
  103172. }
  103173. }
  103174. this._uniformBuffer.update();
  103175. this._afterBind(mesh, this._activeEffect);
  103176. };
  103177. /**
  103178. * Dispose the material.
  103179. * @param forceDisposeEffect Force disposal of the associated effect.
  103180. * @param forceDisposeTextures Force disposal of the associated textures.
  103181. */
  103182. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  103183. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  103184. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  103185. if (forceDisposeTextures) {
  103186. if (this.diffuseTexture) {
  103187. this.diffuseTexture.dispose();
  103188. }
  103189. if (this.reflectionTexture) {
  103190. this.reflectionTexture.dispose();
  103191. }
  103192. }
  103193. this._renderTargets.dispose();
  103194. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103195. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103196. }
  103197. _super.prototype.dispose.call(this, forceDisposeEffect);
  103198. };
  103199. /**
  103200. * Clones the material.
  103201. * @param name The cloned name.
  103202. * @returns The cloned material.
  103203. */
  103204. BackgroundMaterial.prototype.clone = function (name) {
  103205. var _this = this;
  103206. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  103207. };
  103208. /**
  103209. * Serializes the current material to its JSON representation.
  103210. * @returns The JSON representation.
  103211. */
  103212. BackgroundMaterial.prototype.serialize = function () {
  103213. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103214. serializationObject.customType = "BABYLON.BackgroundMaterial";
  103215. return serializationObject;
  103216. };
  103217. /**
  103218. * Gets the class name of the material
  103219. * @returns "BackgroundMaterial"
  103220. */
  103221. BackgroundMaterial.prototype.getClassName = function () {
  103222. return "BackgroundMaterial";
  103223. };
  103224. /**
  103225. * Parse a JSON input to create back a background material.
  103226. * @param source The JSON data to parse
  103227. * @param scene The scene to create the parsed material in
  103228. * @param rootUrl The root url of the assets the material depends upon
  103229. * @returns the instantiated BackgroundMaterial.
  103230. */
  103231. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  103232. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  103233. };
  103234. /**
  103235. * Standard reflectance value at parallel view angle.
  103236. */
  103237. BackgroundMaterial.StandardReflectance0 = 0.05;
  103238. /**
  103239. * Standard reflectance value at grazing angle.
  103240. */
  103241. BackgroundMaterial.StandardReflectance90 = 0.5;
  103242. __decorate([
  103243. BABYLON.serializeAsColor3()
  103244. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  103245. __decorate([
  103246. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103247. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  103248. __decorate([
  103249. BABYLON.serializeAsColor3()
  103250. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  103251. __decorate([
  103252. BABYLON.serialize()
  103253. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  103254. __decorate([
  103255. BABYLON.serialize()
  103256. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  103257. __decorate([
  103258. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103259. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  103260. __decorate([
  103261. BABYLON.serializeAsTexture()
  103262. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  103263. __decorate([
  103264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103265. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  103266. __decorate([
  103267. BABYLON.serialize()
  103268. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  103269. __decorate([
  103270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103271. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  103272. __decorate([
  103273. BABYLON.serializeAsTexture()
  103274. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  103275. __decorate([
  103276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103277. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  103278. __decorate([
  103279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103280. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  103281. __decorate([
  103282. BABYLON.serialize()
  103283. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  103284. __decorate([
  103285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103286. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  103287. __decorate([
  103288. BABYLON.serializeAsVector3()
  103289. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  103290. __decorate([
  103291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103292. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  103293. __decorate([
  103294. BABYLON.serialize()
  103295. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  103296. __decorate([
  103297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103298. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  103299. __decorate([
  103300. BABYLON.serialize()
  103301. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  103302. __decorate([
  103303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103304. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  103305. __decorate([
  103306. BABYLON.serialize()
  103307. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  103308. __decorate([
  103309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103310. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  103311. __decorate([
  103312. BABYLON.serialize()
  103313. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  103314. __decorate([
  103315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103316. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  103317. __decorate([
  103318. BABYLON.serialize()
  103319. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  103320. __decorate([
  103321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103322. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  103323. __decorate([
  103324. BABYLON.serialize()
  103325. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  103326. __decorate([
  103327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103328. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  103329. __decorate([
  103330. BABYLON.serialize()
  103331. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  103332. __decorate([
  103333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103334. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  103335. __decorate([
  103336. BABYLON.serialize()
  103337. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  103338. __decorate([
  103339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103340. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  103341. __decorate([
  103342. BABYLON.serialize()
  103343. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  103344. __decorate([
  103345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103346. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  103347. __decorate([
  103348. BABYLON.serializeAsImageProcessingConfiguration()
  103349. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  103350. return BackgroundMaterial;
  103351. }(BABYLON.PushMaterial));
  103352. BABYLON.BackgroundMaterial = BackgroundMaterial;
  103353. })(BABYLON || (BABYLON = {}));
  103354. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  103355. var __assign = (this && this.__assign) || Object.assign || function(t) {
  103356. for (var s, i = 1, n = arguments.length; i < n; i++) {
  103357. s = arguments[i];
  103358. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  103359. t[p] = s[p];
  103360. }
  103361. return t;
  103362. };
  103363. var BABYLON;
  103364. (function (BABYLON) {
  103365. /**
  103366. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  103367. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  103368. * It also helps with the default setup of your imageProcessing configuration.
  103369. */
  103370. var EnvironmentHelper = /** @class */ (function () {
  103371. /**
  103372. * constructor
  103373. * @param options
  103374. * @param scene The scene to add the material to
  103375. */
  103376. function EnvironmentHelper(options, scene) {
  103377. var _this = this;
  103378. this._errorHandler = function (message, exception) {
  103379. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  103380. };
  103381. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  103382. this._scene = scene;
  103383. this.onErrorObservable = new BABYLON.Observable();
  103384. this._setupBackground();
  103385. this._setupImageProcessing();
  103386. }
  103387. /**
  103388. * Creates the default options for the helper.
  103389. */
  103390. EnvironmentHelper._getDefaultOptions = function () {
  103391. return {
  103392. createGround: true,
  103393. groundSize: 15,
  103394. groundTexture: this._groundTextureCDNUrl,
  103395. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103396. groundOpacity: 0.9,
  103397. enableGroundShadow: true,
  103398. groundShadowLevel: 0.5,
  103399. enableGroundMirror: false,
  103400. groundMirrorSizeRatio: 0.3,
  103401. groundMirrorBlurKernel: 64,
  103402. groundMirrorAmount: 1,
  103403. groundMirrorFresnelWeight: 1,
  103404. groundMirrorFallOffDistance: 0,
  103405. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  103406. groundYBias: 0.00001,
  103407. createSkybox: true,
  103408. skyboxSize: 20,
  103409. skyboxTexture: this._skyboxTextureCDNUrl,
  103410. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103411. backgroundYRotation: 0,
  103412. sizeAuto: true,
  103413. rootPosition: BABYLON.Vector3.Zero(),
  103414. setupImageProcessing: true,
  103415. environmentTexture: this._environmentTextureCDNUrl,
  103416. cameraExposure: 0.8,
  103417. cameraContrast: 1.2,
  103418. toneMappingEnabled: true,
  103419. };
  103420. };
  103421. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  103422. /**
  103423. * Gets the root mesh created by the helper.
  103424. */
  103425. get: function () {
  103426. return this._rootMesh;
  103427. },
  103428. enumerable: true,
  103429. configurable: true
  103430. });
  103431. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  103432. /**
  103433. * Gets the skybox created by the helper.
  103434. */
  103435. get: function () {
  103436. return this._skybox;
  103437. },
  103438. enumerable: true,
  103439. configurable: true
  103440. });
  103441. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  103442. /**
  103443. * Gets the skybox texture created by the helper.
  103444. */
  103445. get: function () {
  103446. return this._skyboxTexture;
  103447. },
  103448. enumerable: true,
  103449. configurable: true
  103450. });
  103451. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  103452. /**
  103453. * Gets the skybox material created by the helper.
  103454. */
  103455. get: function () {
  103456. return this._skyboxMaterial;
  103457. },
  103458. enumerable: true,
  103459. configurable: true
  103460. });
  103461. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  103462. /**
  103463. * Gets the ground mesh created by the helper.
  103464. */
  103465. get: function () {
  103466. return this._ground;
  103467. },
  103468. enumerable: true,
  103469. configurable: true
  103470. });
  103471. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  103472. /**
  103473. * Gets the ground texture created by the helper.
  103474. */
  103475. get: function () {
  103476. return this._groundTexture;
  103477. },
  103478. enumerable: true,
  103479. configurable: true
  103480. });
  103481. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  103482. /**
  103483. * Gets the ground mirror created by the helper.
  103484. */
  103485. get: function () {
  103486. return this._groundMirror;
  103487. },
  103488. enumerable: true,
  103489. configurable: true
  103490. });
  103491. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  103492. /**
  103493. * Gets the ground mirror render list to helps pushing the meshes
  103494. * you wish in the ground reflection.
  103495. */
  103496. get: function () {
  103497. if (this._groundMirror) {
  103498. return this._groundMirror.renderList;
  103499. }
  103500. return null;
  103501. },
  103502. enumerable: true,
  103503. configurable: true
  103504. });
  103505. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  103506. /**
  103507. * Gets the ground material created by the helper.
  103508. */
  103509. get: function () {
  103510. return this._groundMaterial;
  103511. },
  103512. enumerable: true,
  103513. configurable: true
  103514. });
  103515. /**
  103516. * Updates the background according to the new options
  103517. * @param options
  103518. */
  103519. EnvironmentHelper.prototype.updateOptions = function (options) {
  103520. var newOptions = __assign({}, this._options, options);
  103521. if (this._ground && !newOptions.createGround) {
  103522. this._ground.dispose();
  103523. this._ground = null;
  103524. }
  103525. if (this._groundMaterial && !newOptions.createGround) {
  103526. this._groundMaterial.dispose();
  103527. this._groundMaterial = null;
  103528. }
  103529. if (this._groundTexture) {
  103530. if (this._options.groundTexture != newOptions.groundTexture) {
  103531. this._groundTexture.dispose();
  103532. this._groundTexture = null;
  103533. }
  103534. }
  103535. if (this._skybox && !newOptions.createSkybox) {
  103536. this._skybox.dispose();
  103537. this._skybox = null;
  103538. }
  103539. if (this._skyboxMaterial && !newOptions.createSkybox) {
  103540. this._skyboxMaterial.dispose();
  103541. this._skyboxMaterial = null;
  103542. }
  103543. if (this._skyboxTexture) {
  103544. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  103545. this._skyboxTexture.dispose();
  103546. this._skyboxTexture = null;
  103547. }
  103548. }
  103549. if (this._groundMirror && !newOptions.enableGroundMirror) {
  103550. this._groundMirror.dispose();
  103551. this._groundMirror = null;
  103552. }
  103553. if (this._scene.environmentTexture) {
  103554. if (this._options.environmentTexture != newOptions.environmentTexture) {
  103555. this._scene.environmentTexture.dispose();
  103556. }
  103557. }
  103558. this._options = newOptions;
  103559. this._setupBackground();
  103560. this._setupImageProcessing();
  103561. };
  103562. /**
  103563. * Sets the primary color of all the available elements.
  103564. * @param color the main color to affect to the ground and the background
  103565. */
  103566. EnvironmentHelper.prototype.setMainColor = function (color) {
  103567. if (this.groundMaterial) {
  103568. this.groundMaterial.primaryColor = color;
  103569. }
  103570. if (this.skyboxMaterial) {
  103571. this.skyboxMaterial.primaryColor = color;
  103572. }
  103573. if (this.groundMirror) {
  103574. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  103575. }
  103576. };
  103577. /**
  103578. * Setup the image processing according to the specified options.
  103579. */
  103580. EnvironmentHelper.prototype._setupImageProcessing = function () {
  103581. if (this._options.setupImageProcessing) {
  103582. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  103583. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  103584. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  103585. this._setupEnvironmentTexture();
  103586. }
  103587. };
  103588. /**
  103589. * Setup the environment texture according to the specified options.
  103590. */
  103591. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  103592. if (this._scene.environmentTexture) {
  103593. return;
  103594. }
  103595. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  103596. this._scene.environmentTexture = this._options.environmentTexture;
  103597. return;
  103598. }
  103599. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  103600. this._scene.environmentTexture = environmentTexture;
  103601. };
  103602. /**
  103603. * Setup the background according to the specified options.
  103604. */
  103605. EnvironmentHelper.prototype._setupBackground = function () {
  103606. if (!this._rootMesh) {
  103607. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  103608. }
  103609. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  103610. var sceneSize = this._getSceneSize();
  103611. if (this._options.createGround) {
  103612. this._setupGround(sceneSize);
  103613. this._setupGroundMaterial();
  103614. this._setupGroundDiffuseTexture();
  103615. if (this._options.enableGroundMirror) {
  103616. this._setupGroundMirrorTexture(sceneSize);
  103617. }
  103618. this._setupMirrorInGroundMaterial();
  103619. }
  103620. if (this._options.createSkybox) {
  103621. this._setupSkybox(sceneSize);
  103622. this._setupSkyboxMaterial();
  103623. this._setupSkyboxReflectionTexture();
  103624. }
  103625. this._rootMesh.position.x = sceneSize.rootPosition.x;
  103626. this._rootMesh.position.z = sceneSize.rootPosition.z;
  103627. this._rootMesh.position.y = sceneSize.rootPosition.y;
  103628. };
  103629. /**
  103630. * Get the scene sizes according to the setup.
  103631. */
  103632. EnvironmentHelper.prototype._getSceneSize = function () {
  103633. var _this = this;
  103634. var groundSize = this._options.groundSize;
  103635. var skyboxSize = this._options.skyboxSize;
  103636. var rootPosition = this._options.rootPosition;
  103637. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  103638. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103639. }
  103640. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  103641. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  103642. });
  103643. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  103644. if (this._options.sizeAuto) {
  103645. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  103646. this._scene.activeCamera.upperRadiusLimit) {
  103647. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  103648. skyboxSize = groundSize;
  103649. }
  103650. var sceneDiagonalLenght = sceneDiagonal.length();
  103651. if (sceneDiagonalLenght > groundSize) {
  103652. groundSize = sceneDiagonalLenght * 2;
  103653. skyboxSize = groundSize;
  103654. }
  103655. // 10 % bigger.
  103656. groundSize *= 1.1;
  103657. skyboxSize *= 1.5;
  103658. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  103659. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  103660. }
  103661. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103662. };
  103663. /**
  103664. * Setup the ground according to the specified options.
  103665. */
  103666. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  103667. var _this = this;
  103668. if (!this._ground || this._ground.isDisposed()) {
  103669. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  103670. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  103671. this._ground.parent = this._rootMesh;
  103672. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  103673. }
  103674. this._ground.receiveShadows = this._options.enableGroundShadow;
  103675. };
  103676. /**
  103677. * Setup the ground material according to the specified options.
  103678. */
  103679. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  103680. if (!this._groundMaterial) {
  103681. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  103682. }
  103683. this._groundMaterial.alpha = this._options.groundOpacity;
  103684. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  103685. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  103686. this._groundMaterial.primaryColor = this._options.groundColor;
  103687. this._groundMaterial.useRGBColor = false;
  103688. this._groundMaterial.enableNoise = true;
  103689. if (this._ground) {
  103690. this._ground.material = this._groundMaterial;
  103691. }
  103692. };
  103693. /**
  103694. * Setup the ground diffuse texture according to the specified options.
  103695. */
  103696. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  103697. if (!this._groundMaterial) {
  103698. return;
  103699. }
  103700. if (this._groundTexture) {
  103701. return;
  103702. }
  103703. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  103704. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  103705. return;
  103706. }
  103707. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103708. diffuseTexture.gammaSpace = false;
  103709. diffuseTexture.hasAlpha = true;
  103710. this._groundMaterial.diffuseTexture = diffuseTexture;
  103711. };
  103712. /**
  103713. * Setup the ground mirror texture according to the specified options.
  103714. */
  103715. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  103716. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103717. if (!this._groundMirror) {
  103718. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  103719. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  103720. this._groundMirror.anisotropicFilteringLevel = 1;
  103721. this._groundMirror.wrapU = wrapping;
  103722. this._groundMirror.wrapV = wrapping;
  103723. this._groundMirror.gammaSpace = false;
  103724. if (this._groundMirror.renderList) {
  103725. for (var i = 0; i < this._scene.meshes.length; i++) {
  103726. var mesh = this._scene.meshes[i];
  103727. if (mesh !== this._ground &&
  103728. mesh !== this._skybox &&
  103729. mesh !== this._rootMesh) {
  103730. this._groundMirror.renderList.push(mesh);
  103731. }
  103732. }
  103733. }
  103734. }
  103735. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  103736. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  103737. };
  103738. /**
  103739. * Setup the ground to receive the mirror texture.
  103740. */
  103741. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  103742. if (this._groundMaterial) {
  103743. this._groundMaterial.reflectionTexture = this._groundMirror;
  103744. this._groundMaterial.reflectionFresnel = true;
  103745. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  103746. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  103747. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  103748. }
  103749. };
  103750. /**
  103751. * Setup the skybox according to the specified options.
  103752. */
  103753. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  103754. var _this = this;
  103755. if (!this._skybox || this._skybox.isDisposed()) {
  103756. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  103757. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  103758. }
  103759. this._skybox.parent = this._rootMesh;
  103760. };
  103761. /**
  103762. * Setup the skybox material according to the specified options.
  103763. */
  103764. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  103765. if (!this._skybox) {
  103766. return;
  103767. }
  103768. if (!this._skyboxMaterial) {
  103769. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  103770. }
  103771. this._skyboxMaterial.useRGBColor = false;
  103772. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  103773. this._skyboxMaterial.enableNoise = true;
  103774. this._skybox.material = this._skyboxMaterial;
  103775. };
  103776. /**
  103777. * Setup the skybox reflection texture according to the specified options.
  103778. */
  103779. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  103780. if (!this._skyboxMaterial) {
  103781. return;
  103782. }
  103783. if (this._skyboxTexture) {
  103784. return;
  103785. }
  103786. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  103787. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  103788. return;
  103789. }
  103790. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103791. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  103792. this._skyboxTexture.gammaSpace = false;
  103793. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  103794. };
  103795. /**
  103796. * Dispose all the elements created by the Helper.
  103797. */
  103798. EnvironmentHelper.prototype.dispose = function () {
  103799. if (this._groundMaterial) {
  103800. this._groundMaterial.dispose(true, true);
  103801. }
  103802. if (this._skyboxMaterial) {
  103803. this._skyboxMaterial.dispose(true, true);
  103804. }
  103805. this._rootMesh.dispose(false);
  103806. };
  103807. /**
  103808. * Default ground texture URL.
  103809. */
  103810. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  103811. /**
  103812. * Default skybox texture URL.
  103813. */
  103814. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  103815. /**
  103816. * Default environment texture URL.
  103817. */
  103818. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  103819. return EnvironmentHelper;
  103820. }());
  103821. BABYLON.EnvironmentHelper = EnvironmentHelper;
  103822. })(BABYLON || (BABYLON = {}));
  103823. //# sourceMappingURL=babylon.environmentHelper.js.map
  103824. var BABYLON;
  103825. (function (BABYLON) {
  103826. /** Internal class used to store shapes for emitters */
  103827. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  103828. function ParticleSystemSetEmitterCreationOptions() {
  103829. }
  103830. return ParticleSystemSetEmitterCreationOptions;
  103831. }());
  103832. /**
  103833. * Represents a set of particle systems working together to create a specific effect
  103834. */
  103835. var ParticleSystemSet = /** @class */ (function () {
  103836. function ParticleSystemSet() {
  103837. /**
  103838. * Gets the particle system list
  103839. */
  103840. this.systems = new Array();
  103841. }
  103842. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  103843. /**
  103844. * Gets the emitter node used with this set
  103845. */
  103846. get: function () {
  103847. return this._emitterNode;
  103848. },
  103849. enumerable: true,
  103850. configurable: true
  103851. });
  103852. /**
  103853. * Creates a new emitter mesh as a sphere
  103854. * @param options defines the options used to create the sphere
  103855. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  103856. * @param scene defines the hosting scene
  103857. */
  103858. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103859. if (this._emitterNode) {
  103860. this._emitterNode.dispose();
  103861. }
  103862. this._emitterCreationOptions = {
  103863. kind: "Sphere",
  103864. options: options,
  103865. renderingGroupId: renderingGroupId
  103866. };
  103867. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103868. emitterMesh.renderingGroupId = renderingGroupId;
  103869. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103870. material.emissiveColor = options.color;
  103871. emitterMesh.material = material;
  103872. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103873. var system = _a[_i];
  103874. system.emitter = emitterMesh;
  103875. }
  103876. this._emitterNode = emitterMesh;
  103877. };
  103878. /**
  103879. * Starts all particle systems of the set
  103880. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103881. */
  103882. ParticleSystemSet.prototype.start = function (emitter) {
  103883. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103884. var system = _a[_i];
  103885. if (emitter) {
  103886. system.emitter = emitter;
  103887. }
  103888. system.start();
  103889. }
  103890. };
  103891. /**
  103892. * Release all associated resources
  103893. */
  103894. ParticleSystemSet.prototype.dispose = function () {
  103895. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103896. var system = _a[_i];
  103897. system.dispose();
  103898. }
  103899. this.systems = [];
  103900. if (this._emitterNode) {
  103901. this._emitterNode.dispose();
  103902. this._emitterNode = null;
  103903. }
  103904. };
  103905. /**
  103906. * Serialize the set into a JSON compatible object
  103907. * @returns a JSON compatible representation of the set
  103908. */
  103909. ParticleSystemSet.prototype.serialize = function () {
  103910. var result = {};
  103911. result.systems = [];
  103912. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103913. var system = _a[_i];
  103914. result.systems.push(system.serialize());
  103915. }
  103916. if (this._emitterNode) {
  103917. result.emitter = this._emitterCreationOptions;
  103918. }
  103919. return result;
  103920. };
  103921. /**
  103922. * Parse a new ParticleSystemSet from a serialized source
  103923. * @param data defines a JSON compatible representation of the set
  103924. * @param scene defines the hosting scene
  103925. * @param gpu defines if we want GPU particles or CPU particles
  103926. * @returns a new ParticleSystemSet
  103927. */
  103928. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103929. if (gpu === void 0) { gpu = false; }
  103930. var result = new ParticleSystemSet();
  103931. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103932. scene = scene || BABYLON.Engine.LastCreatedScene;
  103933. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103934. var system = _a[_i];
  103935. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103936. }
  103937. if (data.emitter) {
  103938. var options = data.emitter.options;
  103939. switch (data.emitter.kind) {
  103940. case "Sphere":
  103941. result.setEmitterAsSphere({
  103942. diameter: options.diameter,
  103943. segments: options.segments,
  103944. color: BABYLON.Color3.FromArray(options.color)
  103945. }, data.emitter.renderingGroupId, scene);
  103946. break;
  103947. }
  103948. }
  103949. return result;
  103950. };
  103951. return ParticleSystemSet;
  103952. }());
  103953. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103954. })(BABYLON || (BABYLON = {}));
  103955. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103956. var BABYLON;
  103957. (function (BABYLON) {
  103958. /**
  103959. * This class is made for on one-liner static method to help creating particle system set.
  103960. */
  103961. var ParticleHelper = /** @class */ (function () {
  103962. function ParticleHelper() {
  103963. }
  103964. /**
  103965. * This is the main static method (one-liner) of this helper to create different particle systems
  103966. * @param type This string represents the type to the particle system to create
  103967. * @param scene The scene where the particle system should live
  103968. * @param gpu If the system will use gpu
  103969. * @returns the ParticleSystemSet created
  103970. */
  103971. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103972. if (gpu === void 0) { gpu = false; }
  103973. if (!scene) {
  103974. scene = BABYLON.Engine.LastCreatedScene;
  103975. ;
  103976. }
  103977. var token = {};
  103978. scene._addPendingData(token);
  103979. return new Promise(function (resolve, reject) {
  103980. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103981. scene._removePendingData(token);
  103982. return reject("Particle system with GPU is not supported.");
  103983. }
  103984. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103985. scene._removePendingData(token);
  103986. var newData = JSON.parse(data.toString());
  103987. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103988. }, undefined, undefined, undefined, function (req, exception) {
  103989. scene._removePendingData(token);
  103990. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103991. });
  103992. });
  103993. };
  103994. /**
  103995. * Static function used to export a particle system to a ParticleSystemSet variable.
  103996. * Please note that the emitter shape is not exported
  103997. * @param system defines the particle systems to export
  103998. */
  103999. ParticleHelper.ExportSet = function (systems) {
  104000. var set = new BABYLON.ParticleSystemSet();
  104001. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  104002. var system = systems_1[_i];
  104003. set.systems.push(system);
  104004. }
  104005. return set;
  104006. };
  104007. /**
  104008. * Gets or sets base Assets URL
  104009. */
  104010. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  104011. return ParticleHelper;
  104012. }());
  104013. BABYLON.ParticleHelper = ParticleHelper;
  104014. })(BABYLON || (BABYLON = {}));
  104015. //# sourceMappingURL=babylon.particleHelper.js.map
  104016. var BABYLON;
  104017. (function (BABYLON) {
  104018. /**
  104019. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  104020. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  104021. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  104022. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104023. */
  104024. var VideoDome = /** @class */ (function (_super) {
  104025. __extends(VideoDome, _super);
  104026. /**
  104027. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  104028. * @param name Element's name, child elements will append suffixes for their own names.
  104029. * @param urlsOrVideo defines the url(s) or the video element to use
  104030. * @param options An object containing optional or exposed sub element properties
  104031. */
  104032. function VideoDome(name, urlsOrVideo, options, scene) {
  104033. var _this = _super.call(this, name, scene) || this;
  104034. _this._useDirectMapping = false;
  104035. // set defaults and manage values
  104036. name = name || "videoDome";
  104037. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104038. options.clickToPlay = Boolean(options.clickToPlay);
  104039. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  104040. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  104041. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104042. if (options.useDirectMapping === undefined) {
  104043. _this._useDirectMapping = true;
  104044. }
  104045. else {
  104046. _this._useDirectMapping = options.useDirectMapping;
  104047. }
  104048. _this._setReady(false);
  104049. // create
  104050. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  104051. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104052. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  104053. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104054. texture.onLoadObservable.addOnce(function () {
  104055. _this._setReady(true);
  104056. });
  104057. // configure material
  104058. material.useEquirectangularFOV = true;
  104059. material.fovMultiplier = 1.0;
  104060. material.opacityFresnel = false;
  104061. if (_this._useDirectMapping) {
  104062. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104063. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104064. material.diffuseTexture = texture;
  104065. }
  104066. else {
  104067. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104068. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104069. material.reflectionTexture = texture;
  104070. }
  104071. // configure mesh
  104072. _this._mesh.material = material;
  104073. _this._mesh.parent = _this;
  104074. // optional configuration
  104075. if (options.clickToPlay) {
  104076. scene.onPointerUp = function () {
  104077. _this._videoTexture.video.play();
  104078. };
  104079. }
  104080. return _this;
  104081. }
  104082. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  104083. /**
  104084. * Gets the video texture being displayed on the sphere
  104085. */
  104086. get: function () {
  104087. return this._videoTexture;
  104088. },
  104089. enumerable: true,
  104090. configurable: true
  104091. });
  104092. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  104093. /**
  104094. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104095. * Also see the options.resolution property.
  104096. */
  104097. get: function () {
  104098. return this._material.fovMultiplier;
  104099. },
  104100. set: function (value) {
  104101. this._material.fovMultiplier = value;
  104102. },
  104103. enumerable: true,
  104104. configurable: true
  104105. });
  104106. /**
  104107. * Releases resources associated with this node.
  104108. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104109. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104110. */
  104111. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104112. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104113. this._videoTexture.dispose();
  104114. this._mesh.dispose();
  104115. this._material.dispose();
  104116. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104117. };
  104118. return VideoDome;
  104119. }(BABYLON.Node));
  104120. BABYLON.VideoDome = VideoDome;
  104121. })(BABYLON || (BABYLON = {}));
  104122. //# sourceMappingURL=babylon.videoDome.js.map
  104123. var BABYLON;
  104124. (function (BABYLON) {
  104125. /**
  104126. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  104127. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  104128. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  104129. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104130. */
  104131. var PhotoDome = /** @class */ (function (_super) {
  104132. __extends(PhotoDome, _super);
  104133. /**
  104134. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  104135. * @param name Element's name, child elements will append suffixes for their own names.
  104136. * @param urlsOfPhoto define the url of the photo to display
  104137. * @param options An object containing optional or exposed sub element properties
  104138. */
  104139. function PhotoDome(name, urlOfPhoto, options, scene) {
  104140. var _this = _super.call(this, name, scene) || this;
  104141. _this._useDirectMapping = false;
  104142. // set defaults and manage values
  104143. name = name || "photoDome";
  104144. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104145. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104146. if (options.useDirectMapping === undefined) {
  104147. _this._useDirectMapping = true;
  104148. }
  104149. else {
  104150. _this._useDirectMapping = options.useDirectMapping;
  104151. }
  104152. _this._setReady(false);
  104153. // create
  104154. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104155. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104156. // configure material
  104157. material.opacityFresnel = false;
  104158. material.useEquirectangularFOV = true;
  104159. material.fovMultiplier = 1.0;
  104160. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  104161. _this.photoTexture.onLoadObservable.addOnce(function () {
  104162. _this._setReady(true);
  104163. });
  104164. // configure mesh
  104165. _this._mesh.material = material;
  104166. _this._mesh.parent = _this;
  104167. return _this;
  104168. }
  104169. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  104170. /**
  104171. * Gets or sets the texture being displayed on the sphere
  104172. */
  104173. get: function () {
  104174. return this._photoTexture;
  104175. },
  104176. set: function (value) {
  104177. if (this._photoTexture === value) {
  104178. return;
  104179. }
  104180. this._photoTexture = value;
  104181. if (this._useDirectMapping) {
  104182. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104183. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104184. this._material.diffuseTexture = this._photoTexture;
  104185. }
  104186. else {
  104187. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104188. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104189. this._material.reflectionTexture = this._photoTexture;
  104190. }
  104191. },
  104192. enumerable: true,
  104193. configurable: true
  104194. });
  104195. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  104196. /**
  104197. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104198. * Also see the options.resolution property.
  104199. */
  104200. get: function () {
  104201. return this._material.fovMultiplier;
  104202. },
  104203. set: function (value) {
  104204. this._material.fovMultiplier = value;
  104205. },
  104206. enumerable: true,
  104207. configurable: true
  104208. });
  104209. /**
  104210. * Releases resources associated with this node.
  104211. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104212. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104213. */
  104214. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104215. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104216. this._photoTexture.dispose();
  104217. this._mesh.dispose();
  104218. this._material.dispose();
  104219. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104220. };
  104221. return PhotoDome;
  104222. }(BABYLON.Node));
  104223. BABYLON.PhotoDome = PhotoDome;
  104224. })(BABYLON || (BABYLON = {}));
  104225. //# sourceMappingURL=babylon.photoDome.js.map
  104226. var BABYLON;
  104227. (function (BABYLON) {
  104228. BABYLON.Engine.prototype.createQuery = function () {
  104229. return this._gl.createQuery();
  104230. };
  104231. BABYLON.Engine.prototype.deleteQuery = function (query) {
  104232. this._gl.deleteQuery(query);
  104233. return this;
  104234. };
  104235. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  104236. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  104237. };
  104238. BABYLON.Engine.prototype.getQueryResult = function (query) {
  104239. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  104240. };
  104241. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  104242. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104243. this._gl.beginQuery(glAlgorithm, query);
  104244. return this;
  104245. };
  104246. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  104247. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104248. this._gl.endQuery(glAlgorithm);
  104249. return this;
  104250. };
  104251. BABYLON.Engine.prototype._createTimeQuery = function () {
  104252. var timerQuery = this.getCaps().timerQuery;
  104253. if (timerQuery.createQueryEXT) {
  104254. return timerQuery.createQueryEXT();
  104255. }
  104256. return this.createQuery();
  104257. };
  104258. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  104259. var timerQuery = this.getCaps().timerQuery;
  104260. if (timerQuery.deleteQueryEXT) {
  104261. timerQuery.deleteQueryEXT(query);
  104262. return;
  104263. }
  104264. this.deleteQuery(query);
  104265. };
  104266. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  104267. var timerQuery = this.getCaps().timerQuery;
  104268. if (timerQuery.getQueryObjectEXT) {
  104269. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  104270. }
  104271. return this.getQueryResult(query);
  104272. };
  104273. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  104274. var timerQuery = this.getCaps().timerQuery;
  104275. if (timerQuery.getQueryObjectEXT) {
  104276. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  104277. }
  104278. return this.isQueryResultAvailable(query);
  104279. };
  104280. BABYLON.Engine.prototype.startTimeQuery = function () {
  104281. var caps = this.getCaps();
  104282. var timerQuery = caps.timerQuery;
  104283. if (!timerQuery) {
  104284. return null;
  104285. }
  104286. var token = new BABYLON._TimeToken();
  104287. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104288. if (caps.canUseTimestampForTimerQuery) {
  104289. token._startTimeQuery = this._createTimeQuery();
  104290. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  104291. }
  104292. else {
  104293. if (this._currentNonTimestampToken) {
  104294. return this._currentNonTimestampToken;
  104295. }
  104296. token._timeElapsedQuery = this._createTimeQuery();
  104297. if (timerQuery.beginQueryEXT) {
  104298. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104299. }
  104300. else {
  104301. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104302. }
  104303. this._currentNonTimestampToken = token;
  104304. }
  104305. return token;
  104306. };
  104307. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  104308. var caps = this.getCaps();
  104309. var timerQuery = caps.timerQuery;
  104310. if (!timerQuery || !token) {
  104311. return -1;
  104312. }
  104313. if (caps.canUseTimestampForTimerQuery) {
  104314. if (!token._startTimeQuery) {
  104315. return -1;
  104316. }
  104317. if (!token._endTimeQuery) {
  104318. token._endTimeQuery = this._createTimeQuery();
  104319. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  104320. }
  104321. }
  104322. else if (!token._timeElapsedQueryEnded) {
  104323. if (!token._timeElapsedQuery) {
  104324. return -1;
  104325. }
  104326. if (timerQuery.endQueryEXT) {
  104327. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  104328. }
  104329. else {
  104330. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  104331. }
  104332. token._timeElapsedQueryEnded = true;
  104333. }
  104334. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104335. var available = false;
  104336. if (token._endTimeQuery) {
  104337. available = this._getTimeQueryAvailability(token._endTimeQuery);
  104338. }
  104339. else if (token._timeElapsedQuery) {
  104340. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  104341. }
  104342. if (available && !disjoint) {
  104343. var result = 0;
  104344. if (caps.canUseTimestampForTimerQuery) {
  104345. if (!token._startTimeQuery || !token._endTimeQuery) {
  104346. return -1;
  104347. }
  104348. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  104349. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  104350. result = timeEnd - timeStart;
  104351. this._deleteTimeQuery(token._startTimeQuery);
  104352. this._deleteTimeQuery(token._endTimeQuery);
  104353. token._startTimeQuery = null;
  104354. token._endTimeQuery = null;
  104355. }
  104356. else {
  104357. if (!token._timeElapsedQuery) {
  104358. return -1;
  104359. }
  104360. result = this._getTimeQueryResult(token._timeElapsedQuery);
  104361. this._deleteTimeQuery(token._timeElapsedQuery);
  104362. token._timeElapsedQuery = null;
  104363. token._timeElapsedQueryEnded = false;
  104364. this._currentNonTimestampToken = null;
  104365. }
  104366. return result;
  104367. }
  104368. return -1;
  104369. };
  104370. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  104371. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  104372. };
  104373. // We also need to update AbstractMesh as there is a portion of the code there
  104374. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  104375. var engine = this.getEngine();
  104376. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  104377. this._isOccluded = false;
  104378. return;
  104379. }
  104380. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  104381. this._isOccluded = false;
  104382. return;
  104383. }
  104384. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  104385. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  104386. if (isOcclusionQueryAvailable) {
  104387. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  104388. this._isOcclusionQueryInProgress = false;
  104389. this._occlusionInternalRetryCounter = 0;
  104390. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  104391. }
  104392. else {
  104393. this._occlusionInternalRetryCounter++;
  104394. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  104395. this._isOcclusionQueryInProgress = false;
  104396. this._occlusionInternalRetryCounter = 0;
  104397. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  104398. // if strict continue the last state of the object.
  104399. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  104400. }
  104401. else {
  104402. return;
  104403. }
  104404. }
  104405. }
  104406. var scene = this.getScene();
  104407. if (scene.getBoundingBoxRenderer) {
  104408. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  104409. if (!this._occlusionQuery) {
  104410. this._occlusionQuery = engine.createQuery();
  104411. }
  104412. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  104413. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  104414. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  104415. this._isOcclusionQueryInProgress = true;
  104416. }
  104417. };
  104418. })(BABYLON || (BABYLON = {}));
  104419. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  104420. var BABYLON;
  104421. (function (BABYLON) {
  104422. /**
  104423. * Class used to generate noise procedural textures
  104424. */
  104425. var NoiseProceduralTexture = /** @class */ (function (_super) {
  104426. __extends(NoiseProceduralTexture, _super);
  104427. /**
  104428. * Creates a new NoiseProceduralTexture
  104429. * @param name defines the name fo the texture
  104430. * @param size defines the size of the texture (default is 256)
  104431. * @param scene defines the hosting scene
  104432. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  104433. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  104434. */
  104435. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  104436. if (size === void 0) { size = 256; }
  104437. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  104438. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  104439. _this._time = 0;
  104440. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  104441. _this.brightness = 0.2;
  104442. /** Defines the number of octaves to process */
  104443. _this.octaves = 3;
  104444. /** Defines the level of persistence (0.8 by default) */
  104445. _this.persistence = 0.8;
  104446. /** Gets or sets animation speed factor (default is 1) */
  104447. _this.animationSpeedFactor = 1;
  104448. _this._updateShaderUniforms();
  104449. return _this;
  104450. }
  104451. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  104452. var scene = this.getScene();
  104453. if (!scene) {
  104454. return;
  104455. }
  104456. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  104457. this.setFloat("brightness", this.brightness);
  104458. this.setInt("octaves", this.octaves);
  104459. this.setFloat("persistence", this.persistence);
  104460. this.setFloat("timeScale", this._time);
  104461. };
  104462. /** Generate the current state of the procedural texture */
  104463. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  104464. this._updateShaderUniforms();
  104465. _super.prototype.render.call(this, useCameraPostProcess);
  104466. };
  104467. /**
  104468. * Serializes this noise procedural texture
  104469. * @returns a serialized noise procedural texture object
  104470. */
  104471. NoiseProceduralTexture.prototype.serialize = function () {
  104472. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  104473. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  104474. return serializationObject;
  104475. };
  104476. /**
  104477. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  104478. * @param parsedTexture defines parsed texture data
  104479. * @param scene defines the current scene
  104480. * @param rootUrl defines the root URL containing noise procedural texture information
  104481. * @returns a parsed NoiseProceduralTexture
  104482. */
  104483. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  104484. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  104485. return texture;
  104486. };
  104487. return NoiseProceduralTexture;
  104488. }(BABYLON.ProceduralTexture));
  104489. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  104490. })(BABYLON || (BABYLON = {}));
  104491. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  104492. 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 float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \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}","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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\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 mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,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;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*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(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-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;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(outPosition.y,outPosition.z)).r;\nfloat fetchedG=texture(noiseSampler,vec2(outPosition.x+0.33,outPosition.z+0.33)).r;\nfloat fetchedB=texture(noiseSampler,vec2(outPosition.z-0.33,outPosition.y-0.33)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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","noisePixelShader":"\n\nuniform float brightness;\nuniform int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<octaves; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  104493. 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=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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};"};
  104494. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  104495. globalObject["BABYLON"] = BABYLON;
  104496. //backwards compatibility
  104497. if(typeof earcut !== 'undefined') {
  104498. globalObject["Earcut"] = {
  104499. earcut: earcut
  104500. };
  104501. }
  104502. return BABYLON;
  104503. });